從.Net到Java學習系列目錄html
Spring Boot中的文件上傳就是Spring MVC中的文件上傳,將其集成進來了。app
在模板目錄建立一個新的頁面 profile/uploadPage.html
post
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> <h2 class="indigo-text center">Upload</h2> <form th:action="@{/upload}" method="post" enctype="multipart/form-data" class="col m8 s12 offset-m2"> <div class="input-field col s6"> <input type="file" id="file" name="file"/> </div> <div class="col s6 center"> <button class="btn indigo waves-effect waves-light" type="submit" name="save" >Submit <i class="mdi-content-send right"></i> </button> </div> <div class="col s12 center red-text" th:text="${error}" th:if="${error}"> Error during upload </div> <div class="col m8 s12 offset-m2"> <img th:src="@{${picturePath}}" width="100" height="100"/> </div> </form> </body> </html>
除了表單中的 enctype 屬性之外,並無太多值得關注的。文件將會經過 POST 方法發送到 upload URL 上,新建控制器PictureUploadController
學習
@Controller @SessionAttributes("picturePath") public class PictureUploadController { //跳轉到上傳文件的頁面 @RequestMapping("upload") public String uploadPage() { return "profile/uploadPage"; } //處理文件上傳 @RequestMapping(value = "/upload", method = RequestMethod.POST) public String onUpload(MultipartFile file, HttpServletRequest request, RedirectAttributes redirectAttrs, Model model) throws IOException { if (file.isEmpty() || !isImage(file)) { redirectAttrs.addFlashAttribute("error", "Incorrect file.Please upload a picture."); return "redirect:/upload"; } String filePath = request.getSession().getServletContext().getRealPath("pictures/"); Resource picturePath = copyFileToPictures(file,filePath); String _path="/pictures/"+picturePath.getFilename(); model.addAttribute("picturePath",_path); return "profile/uploadPage"; } private Resource copyFileToPictures(MultipartFile file,String filePath) throws IOException { String filename = file.getOriginalFilename(); File tempFile = File.createTempFile("pic", getFileExtension(filename), new FileSystemResource(filePath).getFile()); try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(in, out); } return new FileSystemResource(tempFile); } //判斷上傳文件的類型是不是圖片 private boolean isImage(MultipartFile file) { return file.getContentType().startsWith("image"); } //獲取上傳文件的擴展名 private static String getFileExtension(String name) { return name.substring(name.lastIndexOf(".")); } }
在項目的根目錄下建立 pictures 目錄 ,上述代碼作的第一件事情是在 pictures 目錄下建立一個臨時文件,這個目錄位於項目的根文件夾下,因此要確保該目錄是存在的。在 Java 中,臨時文件只是用來獲取文件系統中惟一的文件標識符的,用戶能夠自行決定是否要刪除它 。用戶提交的文件將會以 MultipartFile 接口的形式注入到控制器中,這個接口提供了多個方法,用來獲取文件的名稱、大小及其內容 。try...with 代碼塊將會自動關閉流,即使出現異常也會如此,從而移除了finally 這樣的樣板式代碼 。咱們還能夠定義上傳文件的功能。
spa
運行預覽:3d
修改控制器PictureUploadController,添加以下代碼:code
//圖片下載 @RequestMapping(value = "/DownloadPic", method = RequestMethod.GET) public void Download(HttpServletRequest req,HttpServletResponse res) { String fileName = "pic2456280610589533697.jpg"; res.setHeader("content-type", "application/octet-stream"); res.setContentType("application/octet-stream"); res.setHeader("Content-Disposition", "attachment;filename=" + fileName); byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = res.getOutputStream(); String filePath = req.getSession().getServletContext().getRealPath("pictures/"); bis = new BufferedInputStream(new FileInputStream(new File(filePath + fileName))); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("success"); }
修改uploadPage.html,添加:orm
<a href="/DownloadPic">下載圖片</a>