文件下載是web開發中常用的場景,但是貌似springmvc沒有過多的介紹,,也許可能比較簡單吧,但是這麼常用的場景,我們還有必要了解下,
文件上傳就不在解,springmvc中只需要配置上傳組件,然後配合使用MultipartFile,就可以輕鬆實現單個文件上傳和批量上傳,而且上傳的文件類型和大小都可以在springmvc 配置文件中配置,這裏就不再贅述
第一種方式使用httpservlet和上傳組件實現,smartupload或者commons-fileUpload都可以:
目前沒有找到官方的smartupload對於springmvc的MultipartResolver接口的實現,網絡的播客也沒有寫關於smartupload和springmvc簡易整合的博客,都是關於在java代碼中整合,個人感覺這樣就沒有整合的意義,根本沒有自動化的感覺,但是由於本人的知識有限,加之目前使用的idea15到期,又不知道怎麼破解,看見eclipse都不想寫代碼,(實話實說,源碼我其實還沒看太懂),說這裏不演示springmvc整合smartupload了,沒有意義,網上一大堆僞整合
servlet實現上傳(注意需要commons-fileupload jar包):
controler方法如下:
//原始的文件httpservlet上傳
@RequestMapping("downfile3")
public String downLoadFile(Model model,HttpServletResponse response,String descFile) throws IOException {
File file=new File("f:\\web\\"+descFile);
if(descFile==null||!file.exists()){
model.addAttribute("msg", "親,您要下載的文件"+descFile+"不存在");
return "load";
}
System.out.println(descFile);
try{
response.reset();
//設置ContentType
response.setContentType("application/octet-stream; charset=utf-8");
//處理中文文件名中文亂碼問題
String fileName=new String(file.getName().getBytes("utf-8"),"ISO-8859-1");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
IOUtils.copy(new FileInputStream(file), response.getOutputStream());
return null;
}catch (Exception e) {
model.addAttribute("msg", "下載失敗");
return "load";
}
}
第二種方式springmvc官方推薦,做了一定的封裝
controler方法代碼如下:
}
//springmvc中支持的下載
@RequestMapping("/downfile2")
public ResponseEntity<byte[]> download() throws IOException {
File file=new File("c:\\ajaxutils.txt");
//處理顯示中文文件名的問題
String fileName=new String(file.getName().getBytes("utf-8"),"ISO-8859-1");
//設置請求頭內容,告訴瀏覽器代開下載窗口
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment",fileName );
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
最後再說點題外話,springmvc文檔中提到了這個方法:
這個方法會直接以流的形式向頁面輸出數據,可以用來處理文檔,和驗證碼問題
//直接返回輸出流,因爲沒有設置請求頭所以不會顯示
@RequestMapping("/downfile")
public StreamingResponseBody handle2() {
return new StreamingResponseBody() {
@Override
public void writeTo(OutputStream outputStream) throws IOException {
HttpHeaders headers = new HttpHeaders();
FileUtils.copyFile(new File("c:\\磊哥.png"), outputStream);
}
};
}