1.1 引入核心JAR包html
SpringMVC实现文件上传,须要再添加两个jar包。一个是文件上传的jar包,一个是其所依赖的IO包。这两个jar包,均在Spring支持库的org.apache.commons中。java
FileUpController.java 完整web
@Controller public class FileUpController { @RequestMapping("/") public String index() { return "index"; } @RequestMapping(value="upload",method=RequestMethod.POST) public String upload(MultipartFile myFile,Model model,HttpServletRequest request) { //获取上传图片存储目录 String path = request.getSession().getServletContext().getRealPath("upload"); System.out.println(path); //获取文件名并使用UUID生成新文件名 String fileName = myFile.getOriginalFilename(); String newFileName = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf(".")); //在指定上传存储目录中建立新文件 File targetFile = new File(path,newFileName); //找不到指定上传图片存储目录,就新建立此目录 if(!targetFile.exists()) { targetFile.mkdirs(); } //将文件写入硬盘 try { myFile.transferTo(targetFile); } catch (IllegalStateException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //将上传后的文件路径传到view model.addAttribute("fileUrl", request.getContextPath()+"/upload"+newFileName); return "upload"; } }
applicationContext.xml:spring
注:必须建立MultipartFile实例。要不出现500错误apache
index.jsp页面:需指定 enctype="multipart/form-data 数组
<body> <form action="${pageContext.request.contextPath }/first.do" method="post" enctype="multipart/form-data"> <h2>文件上传</h2> 文件:<input type="file" name="uploadFile"/><br/><br/> <input type="submit" value="上传"/> </form> </body>
实现效果: 浏览器
若是没有选择要上传的文件,能够经过以下判断代码回到错误页,并配置异常类app
<!-- 配置异常类 报错 --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="defaultErrorView" value="/error.jsp"></property> </bean>
实现效果:dom
<a href="${pageContext.request.contextPath }/download.do?line.jpg">下载</a>
DownloadControll.java 完整 jsp
@Controller public class DownloadController { @RequestMapping(value="download",method=RequestMethod.GET) public ResponseEntity<byte[]> download(String filename,HttpServletRequest request)throws Exception { //下载文件路径 String path = request.getServletContext().getRealPath("upload"); File file = new File(path + "/" + filename); //开始设置http请求头 HttpHeaders headers = new HttpHeaders(); //下载显示的文件名,解决中文名称乱码问题 String downloadFileName = new String(filename.getBytes("UTF-8"),"ISO-8859-1"); //通知浏览器以attachment(下载方式)打开文件。 headers.setContentDispositionFormData("attachment", downloadFileName); //设置mime:application/octet-stream : 二进制流数据(最多见的文件下载)。 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>( FileUtils.readFileToByteArray(file), //把一个文件转换成字节数组返回 headers, //http请求头 HttpStatus.OK //200 ); } }
实现效果:
项目源码下载--->>工程源码下载