SpringMVC:文件上傳及下載
文件上傳是項目開發中最常見的功能之一,SringMVC 可以很好地支持文件的上傳,但是springmvc上下文中默認沒有裝配MultipartReseolver,因此默認情況下其不能處理文件上傳工作。 如果想使用Springmvc的文件上傳功能,則需要在上下文中配置MutilpartResovler。
準備工作
前端表單要求: 爲了能上傳文件,必須將表達的method設置成post , 並將entcype設置爲 multipart/form-data 。 只有這樣的情況下 , 瀏覽器纔會把用戶的選擇的文件已二進制的數據發送給服務器。
對錶單中的enctype 屬性做個詳細的說明:
丶application/x-www=form-urlencoded : 默認方式,只處理表單域中的vale屬性值,採用這種編碼方式的表單會將表單域中的值處理成url 編碼方式。
丶multipart/form-data : 這種編碼方式會二進制流的方式來處理表單數據,這種編碼方式會把文件域指定文件的內容也封裝到請求參數中,不會對字符編碼。
丶text/plain:除了把空格轉換爲 “+” 號外,其他字符都不做編碼處理,這種方式適用直接通過表單發送郵件。
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit">
</form>
一旦設置了enctype爲multipart/form-data ,瀏覽器即會採用二進制的方式處理表單數據,而對於上傳的處理則涉及在服務器端解析原始的http響應。在2003年,apche Sofatware Foundation發佈了開源的Commons FileUploda組件,其很快成爲 Servlet/sp 程序上傳文件的最佳選擇。
、
Servlet3.0規範已經提供方法來 處理文件上傳,但這種上傳需要在Sevlet中完成。而springMVC則提供了更簡單的封裝。
Spring mvc 爲爲文件上傳提供了直接的支持,這種支持是用即插即用的MultipartResolver實現的的。Spring mvcApache Commons FileUpload技術實現了一個MultipartResolver實現類:CommonsMultipartResolver。因此,SpringMVC的文件上傳還需要依賴Apache Commons FileUpload的組件。
在springmvc-servlet.xml進行配置文件如下:
**注意!!!**這個bena的id必須爲:multipartResolver , 否則上傳文件會報400的錯誤!在這裏栽過坑,教訓!
> <!--文件上傳配置-->
> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
> <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內容,默認爲ISO-8859-1 -->
> <property name="defaultEncoding" value="utf-8"/>
> <!-- 上傳文件大小上限,單位爲字節(10485760=10M) -->
> <property name="maxUploadSize" value="10485760"/>
> <property name="maxInMemorySize" value="40960"/>
> </bean>
除此之外,我們還需要導入文件上傳的jar包,commons-fileupload , Maven會自動幫我們導入他的依賴包 commons-io包;
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
我們會使用它的實現類 CommonsMultipartFile , 常用方法
String getOriginalFilename():獲取上傳文件的原名
InputStream getInputStream():獲取文件流
void transferTo(File dest):將上傳文件保存到一個目錄文件中
我們去實際測試一下
方式一:採用流的方式上傳文件
前端
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="upload">
</form>
Controller
必須加上 @RequestParam , 否則也會報錯!作用是用來實現封裝!
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//1.獲得文件名
request.setCharacterEncoding("utf-8");
String filename = file.getOriginalFilename();
if ("".equals(filename)){
return "文件不存在";
}
//2.上傳文件保存路徑
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//3.上傳文件
InputStream is = file.getInputStream();
FileOutputStream os = new FileOutputStream(new File(realPath, filename));
int len = 0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
//4.關閉流
os.close();
is.close();
return "/successful";
}
運行結果:
點擊選擇文件
選擇一個文件,點擊提交:
、
ok已經上傳成功
實現上傳的另一種方式:
//文件上傳:CommonsMultipartFile
@RequestMapping(value = "/upload2")
@ResponseBody
public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上傳文件保存路徑
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//transferTo:將文件寫入到磁盤,參數就是一個文件
file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
return "上傳完畢";
}
文件的下載:
在Controller層加入以下代碼:
@RequestMapping(value = "/download")
public String download(HttpServletResponse response) throws IOException {
//要下載的圖片路徑:,服務器有沒有強,一般下載都有自己公司的圖牀,地址;
String path = "C:/Users/Administrator/Desktop";
String filename = "bz.jpg";
//設置響應頭信息;【固定的不用記,保存即可】
response.reset(); //讓頁面不緩存
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");//二進制流傳輸數據
response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
File file = new File(path,filename);
//輸入流
FileInputStream input = new FileInputStream(file);
//輸出流
ServletOutputStream out = response.getOutputStream();
//執行操作
int len = 0;
byte[] buffer = new byte[1024];
while ((len = input.read(buffer))!=-1){
out.write(buffer,0,len);
out.flush();
}
out.close();
input.close();
return null;
}
indedx.jsp中插入:
<p><a href="${pageContext.request.contextPath}/download">下載圖片</a></p>
看下運行結果:
ok完美。