SpringMVC下文件的上傳與下載以及文件列表的顯示


1、配置好SpringMVC環境-----SpringMVC的HelloWorld快速入門!

導入jar包:commons-fileupload-1.3.1.jar和commons-io-2.4.jar

文件上傳和下載的jar包(百度雲) ---> 資源目錄--->jar包資源--->文件上傳和下載的jar包

2、在SpringMVC配置文件springmvc.xml中配置CommonsMultipartResovler

1 <!-- 配置CommonsMultipartResolver -->
2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
3     <property name="defaultEncoding" value="utf-8"></property>
4     <!-- 以字節為單位 -->
5     <property name="maxUploadSize" value="10485760"></property><!-- 1M=1024x1024 -->
6 </bean>

3、controller方法

 1 @Controller
 2 @RequestMapping("File")
 3 public class FileController {
 4     //文件上傳:表單:POST請求,file類型,enctype="multipart/form-data"
 5     @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
 6     public String testUpload(HttpServletRequest request, @RequestParam(value = "desc", required = false) String desc,
 7             @RequestParam("photo") CommonsMultipartFile fileList[]) throws Exception {
 8         ServletContext servletContext = request.getServletContext();
 9         //獲取服務器下的upload目錄
10         String realPath = servletContext.getRealPath("/upload");
11         File filePath = new File(realPath);
12         //如果目錄不存在,則創建該目錄
13         if (!filePath.exists()) {
14             filePath.mkdir();
15         }
16         OutputStream out;
17         InputStream in;
18         for (CommonsMultipartFile file : fileList) {
19             if (file.getSize() == 0) {
20                 continue;
21             }
22             // 防止重命名uuid_name.jpg
23             String prefix = UUID.randomUUID().toString();
24             prefix = prefix.replace("-", "");
25             String fileName = prefix + "_" + file.getOriginalFilename();
26             out = new FileOutputStream(new File(realPath + "\\" + fileName));
27             in = file.getInputStream();
28             byte[] b = new byte[1024];
29             int c = 0;
30             while ((c = in.read(b)) != -1) {
31                 out.write(b, 0, c);
32                 out.flush();
33             }
34             out.close();
35             in.close();
36         }
37         return "redirect:/File/showFile";
38     }
39     //用ResponseEntity<byte[]> 返回值完成文件下載
40     @RequestMapping(value = "fileDownload")
41     public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, @RequestParam(value = "path") String path)
42             throws Exception {
43         byte[] body = null;
44         // ServletContext servletContext = request.getServletContext();
45         String fileName = path.substring(path.lastIndexOf("_") + 1); //從uuid_name.jpg中截取文件名 46         // String path = servletContext.getRealPath("/WEB-INF/res/" + fileName);
47         File file = new File(path);
48         InputStream in = new FileInputStream(file);
49         body = new byte[in.available()];
50         in.read(body);
51         HttpHeaders headers = new HttpHeaders();
52         fileName = new String(fileName.getBytes("gbk"), "iso8859-1");
53         headers.add("Content-Disposition", "attachment;filename=" + fileName);
54         HttpStatus statusCode = HttpStatus.OK;
55         ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
56         in.close();
57         return response;
58     }
59     //文件列表的顯示
60     @RequestMapping(value = "/showFile")
61     public String showFile(HttpServletRequest request,Model m){
62         ServletContext servletContext = request.getServletContext();
63         String path=servletContext.getRealPath("/upload");
64         File[] fileList = new File(path).listFiles();
65         m.addAttribute("fileList", fileList);
66         return "showFile";
67     }
68 }

文件列表的顯示沒有對其進行處理,應該按時間排序:獲取一個目錄下的所有文件(按時間排序)

4、前台頁面fileUpload.jsp和showFile.jsp

fileUpload.jsp

1 <form action="${pageContext.request.contextPath}/File/fileUpload"method="post" enctype="multipart/form-data">
2     <input type="file" name="photo"><br>
3     <input type="file" name="photo"><br>
4     <input type="file" name="photo"><br>
5     描述:<input type="text" name="desc"><br>
6     <input type="submit" value="上傳">
7 </form>

showFile.jsp

 1 <c:choose>
 2     <c:when test="${not empty fileList }">
 3         <!--索引-->
 4         <c:set var="index" value='1'></c:set>
 5         <c:forEach items="${fileList }" var="file">
 6             <!-- filename:文件的名字,不帶UUID -->
 7             <c:set var="filename" value='${fn:substring(file.name,fn:indexOf(file.name,"_")+1,fn:length(file.name)) }'/>
 8             <!-- filefullname:文件的名字,帶UUID -->
 9             <c:set var="filefullname" value='${fn:split(file.path,"\\\\")[fn:length(fn:split(file.path,"\\\\"))-1] }'></c:set>
10             <!-- rootdir:文件的目錄 -->
11             <c:set var="rootdir" value='${pageContext.request.contextPath}/upload/'></c:set>
12             <div>
13             <img alt='${fileanme }' src='${rootdir.concat(filefullname) }'><!-- 文件的全路徑 -->
14                 <a href="${pageContext.request.contextPath}/File/fileDownload?path=${file.path}">下載</a>
15             </div>
16             <!-- 每行顯示5張圖片 -->
17             <c:if test="${index%5==0 }">
18                 <br>
19             </c:if>
20             <!--索引+1-->
21             <c:set var="index" value='${index+1 }'></c:set>
22         </c:forEach>
23     </c:when>
24     <c:otherwise>
25         暫無數據
26     </c:otherwise>
27 </c:choose>

<c:set>中使用“\\”會報錯,要使用“\\\\”,其他地方使用“\\”即可

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM