本方法是将文件以流的方式,下载到指定的路径。
1.java代码
1. @Controller 2. public class FileController { 3. 4. @RequestMapping(value = "/fileuploads") 5. public String toFileUpload() { 6. return "fileupload"; 7. } 8. 9. @RequestMapping(value = "/fileupload") 10. public String fileUpload(@RequestParam(value = "file") List<MultipartFile> files, HttpServletRequest request) { 11. String msg = ""; 12. // 判断文件是否上传 13. if (!files.isEmpty()) { 14. // 设置上传文件的保存目录 15. String basePath = request.getServletContext().getRealPath("/upload/"); 16. // 判断文件目录是否存在 17. File uploadFile = new File(basePath); 18. if (!uploadFile.exists()) { 19. uploadFile.mkdirs(); 20. } 21. for (MultipartFile file : files) { 22. String originalFilename = file.getOriginalFilename(); 23. if (originalFilename != null && !originalFilename.equals("")) { 24. try { 25. // 对文件名做加UUID值处理 26. originalFilename = UUID.randomUUID() + "_" + originalFilename; 27. file.transferTo(new File(basePath + originalFilename)); 28. } catch (IOException e) { 29. e.printStackTrace(); 30. msg = "文件上传失败!"; 31. } 32. } else { 33. msg = "上传的文件为空!"; 34. } 35. } 36. msg = "文件上传成功!"; 37. } else { 38. msg = "没有文件被上传!"; 39. } 40. request.setAttribute("msg", msg); 41. return "chatroom"; 42. } 43. 44. @ExceptionHandler(MaxUploadSizeExceededException.class) 45. public String handException(MaxUploadSizeExceededException e, HttpServletRequest request) { 46. // System.out.println("我捕获了异常"); 47. request.setAttribute("msg", "文件超过了指定大小,上传失败!"); 48. return "fileupload"; 49. } 50. 51. 52. @RequestMapping(value = "/filedownload") 53. public String toFileDownload(HttpServletRequest request) { 54. return "filedownload"; 55. } 56. 57. @RequestMapping(value = "/fileList") 58. @ResponseBody 59. public String fileList(HttpServletRequest request) { 60. String baseDir = request.getServletContext().getRealPath("/upload"); 61. File baseFile = new File(baseDir); 62. List<String> fileList = null; 63. if (baseFile.exists()) { 64. File[] files = baseFile.listFiles(); 65. fileList = new ArrayList<>(files.length); 66. for (File file : files) { 67. fileList.add(file.getName()); 68. } 69. } 70. // System.out.println(fileList.toString()); 71. String json = JSON.toJSONString(fileList); 72. return json; 73. } 74. 75. 76. @RequestMapping(value = "/download") 77. public ResponseEntity<byte[]> fileDownload(String filename, HttpServletRequest request) throws IOException { 78. String path = request.getServletContext().getRealPath("/upload/"); 79. File file = new File(path + filename); 80. System.out.println("转码前" + filename); 81. filename = this.getFilename(request, filename); 82. System.out.println("转码后" + filename); 83. // 设置响应头通知浏览器下载 84. HttpHeaders headers = new HttpHeaders(); 85. // 将对文件做的特殊处理还原 86. filename = filename.substring(filename.indexOf("_") + 1); 87. headers.setContentDispositionFormData("attachment", filename); 88. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 89. return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK); 90. } 91. 92. // 根据不同的浏览器进行编码设置,返回编码后的文件名 93. public String getFilename(HttpServletRequest request, String filename) throws UnsupportedEncodingException { 94. String[] IEBrowerKeyWords = {"MSIE", "Trident", "Edge"}; 95. String userAgent = request.getHeader("User-Agent"); 96. for (String keyword : IEBrowerKeyWords) { 97. if (userAgent.contains(keyword)) { 98. return URLEncoder.encode(filename, "UTF-8"); 99. } 100. } 101. return new String(filename.getBytes("UTF-8"), "ISO-8859-1"); 102. } 103. 104. 105. }
1. $(function(){ 2. var targer = $("#main2") 3. $.ajax({ 4. url: "fileList", 5. dataType: "json", 6. success: function (data) { 7. for (var i in data) { 8. var a = $("<a></a><br>").text(data[i].substring(data[i].indexOf("_")+1)) 9. a.attr("href", "${pageContext.request.contextPath}/download?filename="+encodeURIComponent(data[i])) 10. targer.append(a) 11. alert(targer) 12. } 13. } 14. }) 15. }
2.js代码
1. function check() { 2. var file = document.getElementById("file"); 3. if (file.value == "") { 4. alert("上传的文件为空") 5. return false; 6. } 7. return true; 8. }
3.jsp代码
1. <div id="main" style="width:500px; margin: 0 auto;"> 2. <form action="fileupload" method="post" enctype="multipart/form-data" onsubmit="return check()"> 3. <input type="file" name="file" id="file" multiple="multiple"><br> 4. <input type="submit" value="上传"> 5. </form> 6. </div> 7. 8. <div id="main2" style="width:500px; margin: 0 auto;"> 9. 10. </div>