MVC檔案上傳與下載
阿新 • • 發佈:2020-07-22
檔案上傳
匯入依賴:
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency>
<!--檔案上傳解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--檔案上傳的字符集--> <property name="defaultEncoding" value="UTF-8"></property> <!--檔案上傳的總大小--> <property name="maxUploadSize" value="5000000000"></property> <!--單個檔案的大小--> <property name="maxUploadSizePerFile" value="5000000"></property> </bean>
/*單檔案上傳*/ @RequestMapping("/fileUpload") public String fileUpdate(MultipartFile upload ,HttpSession session) throws IOException { //獲取絕對路徑 String realPath = session.getServletContext().getRealPath("/upload"); //獲取檔案上傳提交的檔名 String filename = upload.getOriginalFilename(); //組合路徑+上傳操作 upload.transferTo(new File(realPath,filename)); return "index"; }
/*多檔案上傳*/ @RequestMapping("/fileUploads") public String fileUpdates(@RequestParam MultipartFile[] upload ,HttpSession session) throws IOException { //獲取絕對路徑 String realPath = session.getServletContext().getRealPath("/upload"); for (MultipartFile item:upload){ //獲取檔案上傳提交的檔名 String filename = item.getOriginalFilename(); //組合路徑+上傳操作 item.transferTo(new File(realPath,filename)); } return "index"; }
/*檔案下載*/ @RequestMapping("/download") public ResponseEntity<byte[]> dowload(HttpSession session) throws Exception { //獲取絕對路徑 String realPath = session.getServletContext().getRealPath("/upload"); //組裝路徑轉換為file物件 File file=new File(realPath,"新建文字文件.txt"); //設定頭 控制瀏覽器下載對應檔案 HttpHeaders headers=new HttpHeaders(); headers.setContentDispositionFormData("attachment",new String("新建文字文件.txt".getBytes("UTF-8"),"ISO-8859-1")); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK); }