这篇文章主要介绍了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();
}
一般框架会省去许多重复性的工作,但底层的基本原理还是要清楚过程
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。