Spring Boot 單檔案,多檔案上傳,以及將檔案寫入響應中
阿新 • • 發佈:2018-11-19
單檔案上傳
配置檔案設定
@Component public class MultipartConfig { @Bean public MultipartConfigElement multipartConfigElement(){ MultipartConfigFactory factory=new MultipartConfigFactory(); //設定檔案上傳大小 factory.setMaxFileSize("256KB"); //設定總上傳檔案總大小 factory.setMaxRequestSize("512KB"); //設定檔案上傳路徑 factory.setLocation("D:/temp/"); return factory.createMultipartConfig(); } }
單檔案上傳controller
@RequestMapping(value = "upload", method = RequestMethod.POST) @ResponseBody public String upload(@RequestParam("file") MultipartFile file , HttpSession session) { if (!file.isEmpty()) { try { FileCopyUtils.copy(file.getBytes(), new File(uploadPath + file.getOriginalFilename())); } catch (IOException e) { e.printStackTrace(); return "檔案上傳失敗" + e.getMessage(); } return "上傳成功,檔名為" + file.getOriginalFilename(); } else { return "檔案上傳失敗,檔案是空的"; } }
多檔案上傳controller
@RequestMapping(value = "batchUpLoad" ,method = RequestMethod.POST) @ResponseBody public String batchUpLoad(HttpServletRequest request ){ List<MultipartFile> file = ((MultipartHttpServletRequest) request).getFiles("file"); StringBuilder stringBuilder=new StringBuilder(); for (MultipartFile multipartFile : file) { if (!multipartFile.isEmpty()){ try { FileCopyUtils.copy(multipartFile.getBytes(), new File(uploadPath + multipartFile.getOriginalFilename())); stringBuilder.append(multipartFile.getOriginalFilename()+"上傳成功"+"\n"); } catch (IOException e) { e.printStackTrace(); stringBuilder.append(multipartFile.getOriginalFilename()+"上傳失敗"+e.getMessage()+"\n"); return stringBuilder.toString(); } } else { System.out.println("檔案為空"); } } return stringBuilder.toString(); }
html頁面就是簡單的檔案提交頁面
需要說的是,批量上傳檔案,也可以使用 MultipartFile【】 陣列來接收,不過這樣的話,前臺的資料就需要做一定的處理,讓前臺的資料提交為陣列型別
將檔案寫入響應中 (主要用於前臺需要顯示後臺的動態檔案的情況)
@RequestMapping(value = "personInfo")
public void getPersonPicture(HttpServletResponse response) throws IOException {
response.setHeader("Content-Type", URLConnection.guessContentTypeFromName(personPicturePath.getFilename()));
IOUtils.copy(personPicturePath.getInputStream(), response.getOutputStream());
}
github url:springbootfileupload