文件下载是web开发中常用的场景,但是貌似springmvc没有过多的介绍,,也许可能比较简单吧,但是这么常用的场景,我们还有必要了解下,
文件上传就不在解,springmvc中只需要配置上传组件,然后配合使用MultipartFile,就可以轻松实现单个文件上传和批量上传,而且上传的文件类型和大小都可以在springmvc 配置文件中配置,这里就不再赘述
目前没有找到官方的smartupload对于springmvc的MultipartResolver接口的实现,网络的播客也没有写关于smartupload和springmvc简易整合的博客,都是关于在java代码中整合,个人感觉这样就没有整合的意义,根本没有自动化的感觉,但是由于本人的知识有限,加之目前使用的idea15到期,又不知道怎么破解,看见eclipse都不想写代码,(实话实说,源码我其实还没看太懂),说这里不演示springmvc整合smartupload了,没有意义,网上一大堆伪整合
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";
}
}
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);
}
这个方法会直接以流的形式向页面输出数据,可以用来处理文档,和验证码问题
//直接返回输出流,因为没有设置请求头所以不会显示
@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);
}
};
}