SpringMVC框架(四)檔案的上傳下載,上下文路徑
阿新 • • 發佈:2022-04-29
檔案目錄:
SpringMVC配置檔案:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> 9 10 <!-- 配置掃描器 --> 11 <context:component-scan base-package="com.maya.comtroller" /> 12 13 <!-- 配置檢視解析器 --> 14 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 15 <!-- <property name="prefix" value="/WEB-INF/"></property> --> 16 <property name="prefix" value="/"></property> 17 <property name="suffix" value=".jsp"></property> 18 </bean> 19 20 <!-- 對於上傳檔案的解析器 --> 21 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 22 <!-- 上傳檔案的最大值, 單位是b --> 23 <property name="maxUploadSize" value="10240000"></property> 24 <!-- 上傳的單個檔案的大小限制 --> 25 <property name="maxUploadSizePerFile" value="1024000"></property> 26 <!-- 轉換字符集 --> 27 <property name="defaultEncoding" value="utf-8"></property> 28 </bean> 29 30 <!-- 開啟SpringMVC註解驅動 --> 31 <mvc:annotation-driven> 32 <!-- 改成false, 原因是在spring中預設使用的json格式的轉換器是Jackson.jar中的轉換器, 但實際開發中更受歡迎的是fastjson.jar --> 33 <mvc:message-converters register-defaults="false"> 34 <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> 35 <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" /> 36 <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" /> 37 <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> 38 <bean id="fastJsonHttpMessagerConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> 39 <!-- 設定支援的媒體型別 --> 40 <property name="supportedMediaTypes"> 41 <list> 42 <value>text/html; charset=utf-8</value> 43 <value>application/json; charset=utf-8</value> 44 </list> 45 </property> 46 </bean> 47 </mvc:message-converters> 48 </mvc:annotation-driven> 49 </beans>
controller層:
1 package com.maya.comtroller; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.Date; 6 7 import javax.servlet.http.HttpServletRequest; 8 9 import org.apache.commons.io.FileUtils; 10 import org.springframework.http.HttpHeaders; 11 import org.springframework.http.HttpStatus; 12 import org.springframework.http.MediaType; 13 import org.springframework.http.ResponseEntity; 14 import org.springframework.stereotype.Controller; 15 import org.springframework.web.bind.annotation.RequestMapping; 16 import org.springframework.web.bind.annotation.RequestParam; 17 import org.springframework.web.multipart.MultipartFile; 18 19 @Controller 20 @RequestMapping("file") 21 //上傳檔案 22 public class TestFileController { 23 @RequestMapping("/testUpload") 24 public String testUpload( 25 HttpServletRequest request, 26 @RequestParam("myfile") 27 MultipartFile file, 28 String desp) throws IllegalStateException, IOException { 29 30 String path = 31 request.getServletContext().getRealPath("/MyFiles/"); 32 33 Date date = new Date(); 34 35 String orgFileName = date.getTime()+ ""; 36 37 String typeName = file.getOriginalFilename(); 38 39 String orgTypeName = typeName.substring(typeName.lastIndexOf(".")); 40 41 System.out.println(path); 42 // 上傳檔案的原始檔名 43 File orgFile = new File(path + "/" + orgFileName + orgTypeName); 44 45 file.transferTo(orgFile); 46 47 return "success"; 48 } 49 50 //下載檔案 51 @RequestMapping("/downloadFile") 52 public ResponseEntity<byte[]> testDownLoad( 53 HttpServletRequest request, 54 String filename) throws Exception { 55 56 String orgFilename = new String(filename.getBytes("iso-8859-1"), "utf-8"); 57 58 String path = 59 request.getServletContext().getRealPath("/myfiles/"); 60 61 File orgFile = new File(path + "/" + orgFilename); 62 63 // 設定請求頭資訊 64 HttpHeaders hh = new HttpHeaders(); 65 // 告訴前臺, 以(attachement, 就是下載)的方式開啟檔案 66 hh.setContentDispositionFormData("attachment", new String(orgFilename.getBytes("utf-8"), "iso-8859-1")); 67 // 以二進位制流的形式傳輸檔案, 這是最常見的下載方式 68 hh.setContentType(MediaType.APPLICATION_OCTET_STREAM); 69 70 return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(orgFile), hh, 71 HttpStatus.CREATED); 72 } 73 74 }
jsp頁面:
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8" import="java.io.File"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <div style="margin:100px"> 11 <form action="file/testUpload.do" method="post" enctype="multipart/form-data"> 12 <input name="desp" /> 13 <input type="file" multiple="multiple" name="myfile" /><br> 14 <input type="submit" value="Submit" /> 15 </form> 16 17 <hr> 18 <% 19 String path = request.getServletContext().getRealPath("/MyFiles/"); 20 File f = new File(path); 21 File[] files=f.listFiles(); //獲取路徑下的檔名 22 for(File fi:files){ 23 out.print("<a href='file/downloadFile.do?filename="+fi.getName()+"'>"+fi.getName()+"</a><br>"); 24 } 25 %> 26 </div> 27 </body> 28 </html>
這種方式只能進行單檔案的上傳,不建議使用該方式進行多檔案上傳,應考慮其他方式。如果要使用該方式進行多檔案上傳,可以,使用如下程式碼:
from表單中增加一個
multiple="multiple"
1 <form action="<%=basePath %>/file/testUpload.do" method="post"
2 enctype="multipart/form-data">
3 <input name="myfile" multiple="multiple" type="file" /><input type="submit"
4 value="Submit" />
5 </form>
後臺:
1 @Controller
2 @RequestMapping("file")
3 public class TestFileController {
4 @RequestMapping("/testUpload")
5 public String testUpload(
6 HttpServletRequest request,
7 @RequestParam("myfile")
8 MultipartFile[] files,
9 String desp) throws IllegalStateException, IOException {
10
11 String path =
12 request.getServletContext().getRealPath("/files/");
13
14 for(MultipartFile file : files) {
15 Date date = new Date();
16 String orgFileName = date.getTime()+ "";
17 String typeName = file.getOriginalFilename();
18 String orgTypeName = typeName.substring(typeName.lastIndexOf("."));
19 File orgFile = new File(path + "/" + orgFileName + orgTypeName);
20 file.transferTo(orgFile);
21 }
22 }
但是,如果在上傳成功之後的提示頁面通過超連結返回檔案上傳頁面,會報404錯
因為有註解
@RequestMapping("file")
定義了請求的字首是指向 file 下的,所以執行方法最後返回的時候,會從 file 下去尋找檢視層的頁面,所以無法找到
解決方法:
可以通過上下文路徑:
1 <%
2 String basePath = request.getContextPath(); // 上下文路徑
3 %>
1 <%=basePath %>
獲取當前專案名,並寫在請求的路徑中
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>Insert title here</title>
8 <%
9 String basePath = request.getContextPath(); // 上下文路徑
10 %>
11 </head>
12 <body>
13 上傳成功 !
14 <a href="<%=basePath %>/filetest.jsp">返回檔案頁面</a>
15 </body>
16 </html>