I made a small demo first
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>uploadimg.html</title> </head> <body> <form enctype="multipart/form-data" method="post" action="/dim/testUploading"> <input type="file" name="file"/> <input class="uploadBtn" type="submit"value="上传"/> </form> </body> </html>
controller:
@Controller @RequestMapping("/dim") public class UploadingController { //跳转到上传文件的页面 @GetMapping("/uploading") @RequiresPermissions("dim:uploading:uploading") //@RequestMapping(value="/gouploadimg", method = RequestMethod.GET) public String goUploadImg() { return "dim/uploading/uploading"; } //处理文件上传 @RequestMapping(value="/testUploading", method = RequestMethod.POST) public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) { //String contentType = file.getContentType(); //得到上传时的文件名 String fileName = file.getOriginalFilename(); //String filePath = request.getSession().getServletContext().getRealPath("test/"); String filePath = "E:\\Program \\phm\\documents\\test\\" ; try { FileUtil.uploadFile(file.getBytes(), filePath, fileName); } catch (Exception e) { } return "uploading,success"; } }
Tools:
public class FileUtil { public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception { File targetFile = new File(filePath); if (!targetFile.exists()) { targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath + fileName); out.write(file); out.flush(); out.close(); } public static boolean deleteFile(String fileName) { File file = new File(fileName); // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除 if (file.exists() && file.isFile()) { if (file.delete()) { return true; } else { return false; } } else { return false; } } public static String renameToUUID(String fileName) { return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1); } }