Sping boot 多文件上傳

1、配置方法

@Configurationpublic class FileConfig { @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); //// 設置文件大小限制 ,超了,頁面會拋出異常信息,這時候就需要進行異常信息的處理了; factory.setMaxFileSize("520MB"); // KB,MB /// 設置總上傳數據總大小 factory.setMaxRequestSize("1024MB"); // Sets the directory location wherefiles will be stored. // factory.setLocation("路徑地址"); return factory.createMultipartConfig(); }}

2、多文件上傳

@RequestMapping(value = "/adds", method = RequestMethod.POST) public @ResponseBody HashMap<String, Object> handleFileUpload(HttpServletRequest request) { List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file"); String lj = request.getParameter("lj"); HashMap<String, Object> map = new HashMap<String, Object>(); MultipartFile file = null; // BufferedOutputStream stream = null; User u = UserUtil.getUserFromSession(); String filePath = ""; for (int i = 0; i < files.size(); ++i) { file = files.get(i); if (!file.isEmpty()) { try { // 文件保存路徑 Resource resource = new ClassPathResource("config/system.xml"); File filer = resource.getFile(); SAXReader reader = new SAXReader(); Document doc = reader.read(filer); // 載入xml文件 // 對於的路徑//learning/video Node node = doc.selectSingleNode(lj); String ps = node.getStringValue(); long str1 = Calendar.getInstance().getTimeInMillis(); filePath = ps + u.getAccount() + "" + str1 + "_" + file.getOriginalFilename(); /* * byte[] bytes = file.getBytes(); stream = new * BufferedOutputStream(new FileOutputStream(new * File(filePath+file.getOriginalFilename()))); * stream.write(bytes); */ /* stream.close(); */ File targetFile = new File(filePath); if (!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdir(); } if (!targetFile.exists()) { targetFile.createNewFile(); } System.out.println("asda: " + filePath); file.transferTo(targetFile); // 保存文件 map.put("code", 0); map.put("msg", "上傳成功"); map.put("url", filePath); } catch (Exception e) { // stream = null; } } else { } } return map; }

推薦閱讀:

spring-jdbc 目前還是一個主流的廣泛使用的持久化框架嗎?
springboot怎麼學?
關於Spring MVC的教程和例子?
Spring boot與Spring cloud 是什麼關係?

TAG:互聯網 | SpringBoot |