最近做了一些文件上传与下载的模块,今天把它整理了一下。
文件上传与下载的主要实现如下:
@RequestMapping(method=RequestMethod.POST)
public String upload(HttpServletRequest request,
@RequestParam("description") String description,
@RequestParam("file") MultipartFile file,Model model) throws Exception {
// //不使用注解
// MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// //获取file
// MultipartFile file = multipartRequest.getFile("file");
//如果文件不为空,写入上传路径
if(!file.isEmpty()) {
//上传文件路径
String path = request.getSession().getServletContext().getRealPath("/ooxx/");
//上传文件名
String filename = file.getOriginalFilename();
File filepath = new File(path,filename);
//判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件当中
file.transferTo(new File(path + File.separator + filename));
model.addAttribute("filename", filename);
return "download";
} else {
return "error";
}
}
@RequestMapping
public ResponseEntity download(HttpServletRequest request,
@RequestParam("filename") String filename,
Model model)throws Exception {
//下载文件路径
String path = request.getSession().getServletContext().getRealPath("/ooxx/");
//由配置文件获取
// String path=(String) request.getSession().getServletContext().getAttribute("path");
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
// String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
String downloadFielName = URLDecoder.decode(filename, "UTF-8");
File file = new File(path + File.separator + downloadFielName);
//通知浏览器以attachment(下载方式)打开文件
headers.setContentDispositionFormData("attachment", new String(downloadFielName.getBytes("UTF-8"),"iso-8859-1"));
//application/octet-stream : 二进制流数据(最常见的文件下载)。
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);//设置MIME类型
//用FileUpload组件的FileUtils读取文件,并构建成ResponseEntity返回给浏览器
//HttpStatus.CREATED是HTTP的状态码201
return new ResponseEntity(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
页面部分比较简单就不贴出来了,实现的效果是这样的:
实际开发过程中由于使用的Spring版本比较低的,所以一些最新的注解以及方法不能使用,然后使用了一些替代的方法,
另外在项目中使用到的路径是从内存中读取的并不是项目路径,具体的实现在demo中都有。
demo下载地址:http://download.csdn.net/download/lazyrabbitlll/9995875