文件的上傳和下載(maven項目)
前提需要導入依賴
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
然後在springmvc.xml文件中進行相關配置(具體屬性自行百度----其實我也不知道,嘿嘿)
<!--添加multipartResolver的bean支持文件上傳 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:maxUploadSize="802400" p:defaultEncoding="utf-8"/>
一、文件的上傳
在controller中實現上傳的步驟:
- 獲取文件名:String fname = pic.getOriginalFilename();
- 對文件名進行處理(數據庫中存入的文件名是隨機文件名):
-
生成隨機名的步驟: a.獲取文件的後綴名 String ext = FilenameUtils.getExtension(fname); b.生成隨機文件名 String randomName = UUID.randomUUID()+"."+ext;
- 指定上傳文件的物理路徑(imgs爲生成的文件夾):String zPath = req.getServletContext().getRealPath("imgs");
- 構建file對象,實現上傳
-
對路徑進行拼接: File file = new File(zPath+'/'+randomName); FileUtils.copyInputStreamToFile(pic.getInputStream(), file); String savePath = zPath+'/'+randomName; stu.setPicPath(savePath);
文件上傳注意的事項:
- 在含有文件上傳的表單form標籤中加入enctype="multipart/form-data"。
- 在文件上傳的input標籤中的type屬性的file,而且name自己定義,之後的後臺也就是controller需要用到。
- 在controller中必須由MultipartFile pic這個屬性,pic對應name屬性
二、文件的下載
指定要下載的文件:<a href="download.do?fileName=logo.jpg">點擊下載</a>
在controller中實現文件下載的步驟:
- 獲得文件:String fName = req.getServletContext().getRealPath("/imgs/"+fileName);
- 通過文件構建一個輸入流:FileInputStream fis = new FileInputStream(fName);
- 在構建一個緩存區:byte[] by = new byte[fis.available()];其中的fis.available()表示創建一個剛剛好的緩存區,不大不小,剛剛好
- 這個可有可無==預防中文文件名:中文操作系統默認採用GBK,瀏覽器默認解釋的字符編碼格式爲ISO-8859-1
fileName = new String(fileName.getBytes("GBK"),"ISO-8859-1"); - 設置相應頭文件及相關內容:
resq.setHeader("content-disposition", "attachment;filename="+fileName);
resq.setContentType("application/octet-stream");
resq.setContentLength(fis.available());
最後進行讀寫以及關閉操作
讀寫
fis.read(by);//讀
resq.getOutputStream().write(by);//寫
resq.getOutputStream().flush();//刷新
resq.getOutputStream().close();//關閉
fis.close();
至此基於ssm的文件上傳和下載已經全部搞定