spring mvc注解文件上传下载

需要两个包:spring mvc注解文件上传下载

包如何导入就不介绍了,前端代码如下(一定要加enctype="multipart/form-data"让服务器知道是文件上传):

<form action="upload.do" method="post" enctype="multipart/form-data">
<input type="file" id="upimage" name="file" onchange="setImagePreview()"/> <input type="submit" value="Submit" /></form>

java代码:

 import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.ui.Model;
/**
* {@Controller} spring注解,指定此类为controller
* {@RequestMapping} 路径
* @author v_zweiwang
*
*/
@Controller
@RequestMapping("/image")
public class ImageController {
@RequestMapping("/toupload")//用于跳转到上传页面
public String toUpload(){
return "/WEB-INF/html/upload.html";
} @RequestMapping("/upload")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request) {
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SS"); //格式化时间
/**构建图片保存的目录**/
String upTime =dateformat.format(new Date()); //用于区别保存
String path=request.getSession().getServletContext().getRealPath("/");//获取项目在服务器的绝对路径file C:....webApp/ =url http://...webApp/ 不明白就打印path
String fileName = file.getOriginalFilename(); //获得文件名
String filePath="/upload/"+upTime+"/";//文件相对路径
File targetFile = new File(path+filePath,fileName); //新建一个文件
if(!targetFile.exists()){
targetFile.mkdirs();
} //保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(request.getContextPath()+filePath+fileName);
return "redirect:/image/download.do?filepath="+filePath+fileName;//直接重定向下载图片
} @RequestMapping("download")
public ResponseEntity<byte[]> download(HttpServletRequest request,String filepath) throws IOException {
String path=request.getSession().getServletContext().getRealPath("/")+filepath;//获取图片路径 filepath为图片相对路径
System.out.println(path);
File file=new File(path);
HttpHeaders headers = new HttpHeaders();
String fileName=new String("filescan.png".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
headers.setContentDispositionFormData("attachment", fileName); //下载后显示的名字
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED); //向浏览器发送数据
}
}
上一篇:Spring MVC的文件上传和下载


下一篇:Mysql数据库的基本概念和架构