首页 > 代码库 > 转载:SpringMVC:上传与下载
转载:SpringMVC:上传与下载
1 springmvc.xml必须配置:
Java代码
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/>
Java代码
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/>
2 WEB-INF/lib下必加入:commons-fileupload.jar与commons-io-1.4.jar二个文件
3 表单属性为: enctype="multipart/form-data"
工程项目图片如下:
具体代码如下:
FileUploadBean.java
Java代码
- public class FileUploadBean {
- private byte[] file;
- public void setFile(byte[] file) {
- this.file = file;
- }
- public byte[] getFile() {
- return file;
- }
- }
Java代码
- public class FileUploadBean {
- private byte[] file;
- public void setFile(byte[] file) {
- this.file = file;
- }
- public byte[] getFile() {
- return file;
- }
- }
Java代码
- package net.liuzd.web;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.net.BindException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.stereotype.Controller;
- import org.springframework.util.FileCopyUtils;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.web.multipart.MultipartHttpServletRequest;
- import org.springframework.web.multipart.commons.CommonsMultipartFile;
- import org.springframework.web.servlet.ModelAndView;
- /**
- * Title: Description: Copyright: Copyright (c) 2011
- * Company:http://liuzidong.iteye.com/ Makedate:2011-5-27 下午01:52:17
- *
- * @author liuzidong
- * @version 1.0
- * @since 1.0
- *
- */
- @Controller
- public class FileUploadController {
- @RequestMapping(value = "/upload", method = RequestMethod.POST)
- public ModelAndView onSubmit(HttpServletRequest request,
- HttpServletResponse response, BindException errors)
- throws Exception {
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
- .getFile("file");
- String name = multipartRequest.getParameter("name");
- System.out.println("name: " + name);
- // 获得文件名:
- String realFileName = file.getOriginalFilename();
- System.out.println("获得文件名:" + realFileName);
- // 获取路径
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "images/";
- // 创建文件
- File dirPath = new File(ctxPath);
- if (!dirPath.exists()) {
- dirPath.mkdir();
- }
- File uploadFile = new File(ctxPath + realFileName);
- FileCopyUtils.copy(file.getBytes(), uploadFile);
- request.setAttribute("files", loadFiles(request));
- return new ModelAndView("success");
- }
- @RequestMapping(value = "/upload2", method = RequestMethod.POST)
- public ModelAndView onSubmit2(HttpServletRequest request,
- HttpServletResponse response, BindException errors)
- throws Exception {
- // 转型为MultipartHttpRequest
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- // 根据前台的name名称得到上传的文件
- MultipartFile file = multipartRequest.getFile("file");
- // 获得文件名:
- String realFileName = file.getOriginalFilename();
- // 获取路径
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "\\" + "images\\";
- // 创建文件
- File dirPath = new File(ctxPath);
- if (!dirPath.exists()) {
- dirPath.mkdir();
- }
- File uploadFile = new File(ctxPath + realFileName);
- FileCopyUtils.copy(file.getBytes(), uploadFile);
- request.setAttribute("files", loadFiles(request));
- return new ModelAndView("success");
- }
- @RequestMapping(value = "/upload3", method = RequestMethod.POST)
- public String upload(@RequestParam("file")
- MultipartFile image, HttpServletRequest request) throws IOException {
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "\\" + "images\\";
- System.out.println("路径:" + ctxPath);
- File file = new File(ctxPath + "/" + image.getOriginalFilename());
- // FileCopyUtils.copy(image.getBytes(),new
- // File(ctxPath+"/"+image.getOriginalFilename()));
- try {
- image.transferTo(file); // 保存上传的文件
- } catch (IllegalStateException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- request.setAttribute("files", loadFiles(request));
- return "success";
- }
- // 多文件上传
- @RequestMapping(value = "/upload4", method = RequestMethod.POST)
- public ModelAndView fileUpload(HttpServletRequest request,
- HttpServletResponse response, BindException errors)
- throws Exception {
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "\\" + "images\\";
- File file = new File(ctxPath);
- if (!file.exists()) {
- file.mkdir();
- }
- String fileName = null;
- for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
- // 上传文件名
- // System.out.println("key: " + entity.getKey());
- MultipartFile mf = entity.getValue();
- fileName = mf.getOriginalFilename();
- File uploadFile = new File(ctxPath + fileName);
- FileCopyUtils.copy(mf.getBytes(), uploadFile);
- }
- request.setAttribute("files", loadFiles(request));
- return new ModelAndView("success");
- }
- // @ModelAttribute("files")//此属性用于初始类时调用,但上传文件后不能时时反应上传文件个数,不适合动态数据
- public List<String> loadFiles(HttpServletRequest request) {
- List<String> files = new ArrayList<String>();
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "\\" + "images\\";
- File file = new File(ctxPath);
- if (file.exists()) {
- File[] fs = file.listFiles();
- String fname = null;
- for (File f : fs) {
- fname = f.getName();
- if (f.isFile()) {
- files.add(fname);
- }
- }
- }
- return files;
- }
- @RequestMapping("/download/{fileName}")
- public ModelAndView download(@PathVariable("fileName")
- String fileName, HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- response.setContentType("text/html;charset=utf-8");
- request.setCharacterEncoding("UTF-8");
- java.io.BufferedInputStream bis = null;
- java.io.BufferedOutputStream bos = null;
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "\\" + "images\\";
- String downLoadPath = ctxPath + fileName;
- System.out.println(downLoadPath);
- try {
- long fileLength = new File(downLoadPath).length();
- response.setContentType("application/x-msdownload;");
- response.setHeader("Content-disposition", "attachment; filename="
- + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
- response.setHeader("Content-Length", String.valueOf(fileLength));
- bis = new BufferedInputStream(new FileInputStream(downLoadPath));
- bos = new BufferedOutputStream(response.getOutputStream());
- byte[] buff = new byte[2048];
- int bytesRead;
- while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
- bos.write(buff, 0, bytesRead);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (bis != null)
- bis.close();
- if (bos != null)
- bos.close();
- }
- return null;
- }
- }
Java代码
- package net.liuzd.web;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.net.BindException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.stereotype.Controller;
- import org.springframework.util.FileCopyUtils;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.web.multipart.MultipartHttpServletRequest;
- import org.springframework.web.multipart.commons.CommonsMultipartFile;
- import org.springframework.web.servlet.ModelAndView;
- /**
- * Title: Description: Copyright: Copyright (c) 2011
- * Company:http://liuzidong.iteye.com/ Makedate:2011-5-27 下午01:52:17
- *
- * @author liuzidong
- * @version 1.0
- * @since 1.0
- *
- */
- @Controller
- public class FileUploadController {
- @RequestMapping(value = "/upload", method = RequestMethod.POST)
- public ModelAndView onSubmit(HttpServletRequest request,
- HttpServletResponse response, BindException errors)
- throws Exception {
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
- .getFile("file");
- String name = multipartRequest.getParameter("name");
- System.out.println("name: " + name);
- // 获得文件名:
- String realFileName = file.getOriginalFilename();
- System.out.println("获得文件名:" + realFileName);
- // 获取路径
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "images/";
- // 创建文件
- File dirPath = new File(ctxPath);
- if (!dirPath.exists()) {
- dirPath.mkdir();
- }
- File uploadFile = new File(ctxPath + realFileName);
- FileCopyUtils.copy(file.getBytes(), uploadFile);
- request.setAttribute("files", loadFiles(request));
- return new ModelAndView("success");
- }
- @RequestMapping(value = "/upload2", method = RequestMethod.POST)
- public ModelAndView onSubmit2(HttpServletRequest request,
- HttpServletResponse response, BindException errors)
- throws Exception {
- // 转型为MultipartHttpRequest
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- // 根据前台的name名称得到上传的文件
- MultipartFile file = multipartRequest.getFile("file");
- // 获得文件名:
- String realFileName = file.getOriginalFilename();
- // 获取路径
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "\\" + "images\\";
- // 创建文件
- File dirPath = new File(ctxPath);
- if (!dirPath.exists()) {
- dirPath.mkdir();
- }
- File uploadFile = new File(ctxPath + realFileName);
- FileCopyUtils.copy(file.getBytes(), uploadFile);
- request.setAttribute("files", loadFiles(request));
- return new ModelAndView("success");
- }
- @RequestMapping(value = "/upload3", method = RequestMethod.POST)
- public String upload(@RequestParam("file")
- MultipartFile image, HttpServletRequest request) throws IOException {
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "\\" + "images\\";
- System.out.println("路径:" + ctxPath);
- File file = new File(ctxPath + "/" + image.getOriginalFilename());
- // FileCopyUtils.copy(image.getBytes(),new
- // File(ctxPath+"/"+image.getOriginalFilename()));
- try {
- image.transferTo(file); // 保存上传的文件
- } catch (IllegalStateException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- request.setAttribute("files", loadFiles(request));
- return "success";
- }
- // 多文件上传
- @RequestMapping(value = "/upload4", method = RequestMethod.POST)
- public ModelAndView fileUpload(HttpServletRequest request,
- HttpServletResponse response, BindException errors)
- throws Exception {
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "\\" + "images\\";
- File file = new File(ctxPath);
- if (!file.exists()) {
- file.mkdir();
- }
- String fileName = null;
- for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
- // 上传文件名
- // System.out.println("key: " + entity.getKey());
- MultipartFile mf = entity.getValue();
- fileName = mf.getOriginalFilename();
- File uploadFile = new File(ctxPath + fileName);
- FileCopyUtils.copy(mf.getBytes(), uploadFile);
- }
- request.setAttribute("files", loadFiles(request));
- return new ModelAndView("success");
- }
- // @ModelAttribute("files")//此属性用于初始类时调用,但上传文件后不能时时反应上传文件个数,不适合动态数据
- public List<String> loadFiles(HttpServletRequest request) {
- List<String> files = new ArrayList<String>();
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "\\" + "images\\";
- File file = new File(ctxPath);
- if (file.exists()) {
- File[] fs = file.listFiles();
- String fname = null;
- for (File f : fs) {
- fname = f.getName();
- if (f.isFile()) {
- files.add(fname);
- }
- }
- }
- return files;
- }
- @RequestMapping("/download/{fileName}")
- public ModelAndView download(@PathVariable("fileName")
- String fileName, HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- response.setContentType("text/html;charset=utf-8");
- request.setCharacterEncoding("UTF-8");
- java.io.BufferedInputStream bis = null;
- java.io.BufferedOutputStream bos = null;
- String ctxPath = request.getSession().getServletContext().getRealPath(
- "/")
- + "\\" + "images\\";
- String downLoadPath = ctxPath + fileName;
- System.out.println(downLoadPath);
- try {
- long fileLength = new File(downLoadPath).length();
- response.setContentType("application/x-msdownload;");
- response.setHeader("Content-disposition", "attachment; filename="
- + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
- response.setHeader("Content-Length", String.valueOf(fileLength));
- bis = new BufferedInputStream(new FileInputStream(downLoadPath));
- bos = new BufferedOutputStream(response.getOutputStream());
- byte[] buff = new byte[2048];
- int bytesRead;
- while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
- bos.write(buff, 0, bytesRead);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (bis != null)
- bis.close();
- if (bos != null)
- bos.close();
- }
- return null;
- }
- }
spring.xml
Java代码
- <?xml version="1.0" encoding="UTF-8" ?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <!--
- 自动搜索@Controller标注的类
- 用于指明系统从哪个路径下寻找controller,然后提前初始化这些对象。
- -->
- <context:component-scan base-package="net.liuzd.web" />
- <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 -->
- <bean
- class="org.springframework.web.servlet.view.InternalResourceViewResolver"
- p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8">
- <property name="maxUploadSize">
- <value>104857600</value>
- </property>
- <property name="maxInMemorySize">
- <value>4096</value>
- </property>
- </bean>
- </beans>
Java代码
- <?xml version="1.0" encoding="UTF-8" ?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <!--
- 自动搜索@Controller标注的类
- 用于指明系统从哪个路径下寻找controller,然后提前初始化这些对象。
- -->
- <context:component-scan base-package="net.liuzd.web" />
- <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 -->
- <bean
- class="org.springframework.web.servlet.view.InternalResourceViewResolver"
- p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8">
- <property name="maxUploadSize">
- <value>104857600</value>
- </property>
- <property name="maxInMemorySize">
- <value>4096</value>
- </property>
- </bean>
- </beans>
success.jsp
Java代码
- <%@ taglib prefix="c" uri="/WEB-INF/c.tld"%>
- <h1>Upload Successful</h1>
- <c:forEach var="month" items="${files}">
- <li><a href=http://www.mamicode.com/"${pageContext.request.contextPath}/download/${month}.do">${month}</a></li>
- </c:forEach>
- <hr><br>
- <a href=http://www.mamicode.com/"${pageContext.request.contextPath}/index.jsp">返回</a>
Java代码
- <%@ taglib prefix="c" uri="/WEB-INF/c.tld"%>
- <h1>Upload Successful</h1>
- <c:forEach var="month" items="${files}">
- <li><a href=http://www.mamicode.com/"${pageContext.request.contextPath}/download/${month}.do">${month}</a></li>
- </c:forEach>
- <hr><br>
- <a href=http://www.mamicode.com/"${pageContext.request.contextPath}/index.jsp">返回</a>
web.xml
Java代码
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <context-param>
- <param-name>log4jConfigLocation</param-name>
- <param-value>/WEB-INF/classes/log4j.properties</param-value>
- </context-param>
- <context-param>
- <param-name>log4jRefreshInterval</param-name>
- <param-value>60000</param-value>
- </context-param>
- <context-param>
- <param-name>log4jExposeWebAppRoot</param-name>
- <param-value>false</param-value>
- </context-param>
- <listener>
- <listener-class>
- org.springframework.web.util.Log4jConfigListener
- </listener-class>
- </listener>
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>
- org.springframework.web.filter.CharacterEncodingFilter
- </filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>false</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>*.do</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <servlet>
- <servlet-name>springmvc</servlet-name>
- <servlet-class>
- org.springframework.web.servlet.DispatcherServlet
- </servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:springmvc.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>springmvc</servlet-name>
- <url-pattern>*.do</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
参考:http://a52071453.iteye.com/blog/1559005
转载:SpringMVC:上传与下载
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。