參考html
xml <!--springmvc 上傳--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
xml <!--文件上傳--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--限制文件大小--> <property name="maxUploadSize" value="10485760"></property> <property name="defaultEncoding" value="UTF-8"></property> </bean>
html <html> <head> <title>上傳</title> </head> <body> <%--使用post請求,enctype="multipart/form-data"--%> <form action="/upload.do" method="post" enctype="multipart/form-data"> <label>頭像</label><input type="file" name="file"><br> <label>用戶名</label><input type="text" value="" placeholder="用戶名" name="username"><br> <label>密碼</label><input type="password" value="" placeholder="密碼" name="password"><br> <input type="submit" value="提交"> </form> </body> </html>
controller層
java @RequestMapping(value = "/upload.do") @ResponseBody public void testUpload( HttpServletRequest request, HttpServletResponse response, User user, @RequestParam(value = "file") MultipartFile file) throws IOException { // 獲取用戶信息 System.out.println("用戶名"); System.out.println(user.getUsername()); System.out.println("密碼"); System.out.println(user.getPassword()); // 獲取文件名 String filename = file.getOriginalFilename(); System.out.println(filename); // 獲取絕對路徑 String upload_Path = request.getRealPath("/upload"); // 路徑處理 String file_path = upload_Path + "//" + UUID.randomUUID() + filename; // 判斷路徑是否存在若是沒有就建立 File file1 = new File(file_path); if (!file1.getParentFile().exists()) { file1.getParentFile().mkdirs(); } // 將文件file裏的內容複製到file1裏 file.transferTo(file1); }
java
jsp頁面web
<html> <head> <title>Title</title> </head> <body> <a href="download.do?filename=f12c1a77-158f-466f-b272-33144f668de3_4Ib-a8g9aA.jpg">下載</a> </body> </html>
controller層
java @RequestMapping("/download") public ResponseEntity<byte[]> downloadTest( HttpServletRequest request, @RequestParam("filename") String filename, Model model) throws IOException { filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8"); // 文件下載路徑 String path = request.getRealPath("/upload/"); System.out.println("path:" + path); File file = new File(path + File.separator + filename); HttpHeaders httpHeaders = new HttpHeaders(); // 解決文件名的亂碼問題 String downloadFileName = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); System.out.println("downloadFileName" + downloadFileName); // 以attachment方式(下載)打開文件 httpHeaders.setContentDispositionFormData("attachment", downloadFileName); // 二進制流數據,常見的文件下載 httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>( FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.CREATED); }
spring