springmvc模式下的上传和下载

接触了springmvc模式后,对上一次的上传与下载进行优化,

上次请看这里

此处上传的功能依旧是采用表格上传。文件格式依旧是

    <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">

后台则是

 @RequestMapping("/upload")
public String upload(MultipartFile file,String userName,HttpServletRequest request) throws IOException {
String filename = file.getOriginalFilename(); String suffix = filename.substring(filename.lastIndexOf(".")); if(suffix.equalsIgnoreCase(".jpg")){
String uuid = UUID.randomUUID().toString();
//FileUtils.copyInputStreamToFile(file.getInputStream(),new File("E://"+uuid+suffix)); file.transferTo(new File("D://"+System.currentTimeMillis()+suffix));//位置存储在硬盘上
// file.transferTo(new File(request.getServletContext().getRealPath("/")+"static/userImages/"+file));
// 存储在项目里的目录下
request.setAttribute("result","上传成功");
return "/result.jsp";
}else{
request.setAttribute("result","上传失败");
return "/result.jsp";
}
}

相比之前的传统式上传,springmvc模式下封装了许多繁琐的过程,通过transferTo即可实现一些相应的操作

而下载也是相应的简化了许多

@RequestMapping("/download")
public void download(String filename, HttpServletResponse response, HttpServletRequest request) throws IOException {
response.setHeader("content-disposition","attachment;filename="+filename); ServletOutputStream outputStream = response.getOutputStream(); String path = request.getServletContext().getRealPath("images"); File file = new File(path,filename); byte[] bytes = FileUtils.readFileToByteArray(file); outputStream.write(bytes); outputStream.close();
}

一般框架会省去许多重复性的工作,但底层的基本原理还是要清楚过程

上一篇:This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed(在64位模式下运行安装了32位的Oracle客户端组件时,会发生此问题)


下一篇:Use Reentrant Functions for Safer Signal Handling(译:使用可重入函数进行更安全的信号处理)