一:引入必要的包
<!--文件上傳--> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
二:在spring-service中配置
<!-- 支持上傳文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <property name="maxUploadSize" value="10485760000"></property> <property name="maxInMemorySize" value="40960"></property> </bean>
三:文件上傳
3.1 實現方法
/** * 文件上傳 * @param file * @param request * @return */ public JSONObject uploadFile(MultipartFile file, HttpServletRequest request){ //獲取文件名稱 String fileName = file.getOriginalFilename(); //獲取文件存放路徑 String path = request.getSession().getServletContext().getRealPath("").concat("/uploadFile"); // String path = getUploadPath(fileName,request); //上傳文件 File targetFile = new File(path, fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } //保存 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); return resultErrorJson(fileName); } logger.info(fileName+"文件上傳成功"); JSONObject jsonObject = new JSONObject(); jsonObject.put("key","true"); jsonObject.put("name",fileName); jsonObject.put("path",path+"/"+fileName); return jsonObject; }
3.2 controller層
@RequestMapping(value="/upload") @ResponseBody public JSONObject upload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request){ fileOperation = new FileOperation(); //返回文件后的文件路徑 return fileOperation.uploadFile(file,request); }
3.3 文本遞交的時候 注意提交格式
<form action="/file/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="提交"> </form>
四:文件下載
/** * 下載文件 * @param fileName 文件模板 * HttpServletRequest request, * @param response response請求 */ public boolean download(String fileName, HttpServletRequest request,HttpServletResponse response) { try { response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); String path = request.getSession().getServletContext().getRealPath("")+"/uploadFile/"+fileName; File tempFile =new File(path); InputStream inputStream = new FileInputStream(tempFile); OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } os.flush(); os.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("文件下載失敗"); return false; }catch (IOException e) { e.printStackTrace(); System.out.println("文件下載失敗"); return false; } return true; }
五 刪除文件
/** * 通過文件絕對路徑 刪除單個文件 * @param filePath */ public boolean delFile(String filePath) { File delFile = new File(filePath); if(delFile.isFile() && delFile.exists()) { delFile.delete(); logger.info("刪除文件成功"); return true; }else { logger.info("沒有該文件,刪除失敗"); return false; } }