前言:
Web项目中,文件上传功能几乎是必不可少的,实现的技术有很多,今天我们来学习如何使用SpringMVC框架完成文件的上传以及下载。
代码:
单文件上传
1.底层使用的是Apache fileupload组件完成上传,SpringMVC只是进行了封装,让开发者使用起来更加方便,所以首先需要引入fileupload组件的依赖。
dependency> groupId>commons-iogroupId> artifactId>commons-ioartifactId> version>1.3.2version> dependency>
dependency> groupId>commons-fileuploadgroupId> artifactId>commons-fileuploadartifactId> version>1.2.1version> dependency>
2.JSP 1.input的type设置为file。 2.form表单的method设置为post。(get请求只会将文件名传给后台) 3.form表单的enctype设置为multipart/form-data,以二进制的形式传输数据。
<%@ page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8'%> <%@ taglib prefix='c' uri='http://java./jsp/jstl/core' %> <% String path = request.getContextPath(); String basePath = request.getScheme()+'://'+request.getServerName()+':'+request.getServerPort()+path+'/'; %> '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www./TR/html4/loose.dtd'>
'Content-Type' content='text/html; charset=UTF-8'>
<>if test='${filePath!=null }'> 上传的图片 '300px' src='<%=basePath %>${filePath}'/> if>
如果上传成功,返回当前页面,展示上传成功的图片,这里需要使用JSTL标签进行判断。
pom文件中引入JSTL依赖。
dependency> groupId>jstlgroupId> artifactId>jstlartifactId> version>1.2version> dependency> dependency> groupId>taglibsgroupId> artifactId>standardartifactId> version>1.1.2version> dependency>
3.业务方法,使用MultipartFile对象作为参数,接收前端发送过来的文件,并完成上传操作。
@RequestMapping(value='/upload', method = RequestMethod.POST) public String upload(@RequestParam(value='img')MultipartFile img, HttpServletRequest request) throws Exception { //getSize()方法获取文件的大小来判断是否有上传文件 if (img.getSize() > 0) { //获取保存上传文件的file文件夹绝对路径 String path = request.getSession().getServletContext().getRealPath('file'); //获取上传文件名 String fileName = img.getOriginalFilename(); File file = new File(path, fileName); img.transferTo(file); //保存上传之后的文件路径 request.setAttribute('filePath', 'file/'+fileName); return 'upload'; } return 'error'; }
4.springmvc.xml配置CommonsMultipartResolver。
bean id='multipartResolver' class='org.springframework.web.multipart.commons.CommonsMultipartResolver'> property name='defaultEncoding' value='utf-8'/> property name='maxUploadSize' value='1048576'/> property name='maxUploadSizePerFile' value='1048576'/> bean>
bean class='org.springframework.web.servlet.handler.SimpleMappingExceptionResolver'> property name='defaultErrorView' value='/error.jsp'/> bean>
5.运行。
多文件上传
1.JSP。
<%@ page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8'%> <%@ taglib prefix='c' uri='http://java./jsp/jstl/core' %> <% String path = request.getContextPath(); String basePath = request.getScheme()+'://'+request.getServerName()+':'+request.getServerPort()+path+'/'; %> '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www./TR/html4/loose.dtd'>
'Content-Type' content='text/html; charset=UTF-8'>
<>if test='${filePaths!=null }'> 上传的图片 '${filePaths }' var='filePath'> '300px' src='<%=basePath %>${filePath}'/> if>
2.业务方法,使用MultipartFile数组对象接收上传的多个文件。
@RequestMapping(value='/uploads', method = RequestMethod.POST) public String uploads(@RequestParam MultipartFile[] imgs, HttpServletRequest request) throws Exception { //创建集合,保存上传后的文件路径 List filePaths = new ArrayList(); for (MultipartFile img : imgs) { if (img.getSize() > 0) { String path = request.getSession().getServletContext().getRealPath('file'); String fileName = img.getOriginalFilename(); File file = new File(path, fileName); filePaths.add('file/'+fileName); img.transferTo(file); } } request.setAttribute('filePaths', filePaths); return 'uploads'; }
3.运行。
文件下载
1.JSP,使用超链接,下载之前上传的logo.jpg。
<%@ page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8'%> '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www./TR/html4/loose.dtd'>
'Content-Type' content='text/html; charset=UTF-8'>
'download?fileName=logo.jpg'>下载图片
2.业务方法。
@RequestMapping('/download') public void downloadFile(String fileName,HttpServletRequest request, HttpServletResponse response){ if(fileName!=null){ //获取file绝对路径 String realPath = request.getServletContext().getRealPath('file/'); File file = new File(realPath,fileName); OutputStream out = null; if(file.exists()){ //设置下载完毕不打开文件 response.setContentType('application/force-download'); //设置文件名 response.setHeader('Content-Disposition', 'attachment;filename='+fileName); try { out = response.getOutputStream(); out.write(FileUtils.readFileToByteArray(file)); out.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(out != null){ try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } }
3.运行。
源码:
链接: https://pan.baidu.com/s/1pMnp0jL 密码: q462
|