接触了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(); }
一般框架会省去许多重复性的工作,但底层的基本原理还是要清楚过程
原文地址:https://www.cnblogs.com/lin530/p/11794769.html
时间: 2024-10-07 16:41:33