今天通过各种手段做了一个springmvc简单实现文件上传下载的功能,特别记录在这里以备以后查询,并请各位大神大牛指导代码与设计中的不足。
上传文件------展示文件库中所有的文件-------点击下载按钮下载
源代码在附件中
web.xml代码:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <!-- spring mvc 拦截 start --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-servlet.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> <!-- spring mvc 拦截 end --> <!-- 编码问题 start--> <filter> <filter-name>Set Character Encoding</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>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>Set Character Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 编码问题 end--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
springmvc配置文件代码spring-servlet.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <context:component-scan base-package="springapp" /> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/view/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置 文件上传 start --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="1000000" /> </bean> <!-- 配置 文件上传 end --> </beans>
文件上传的页面uploadFile.jsp
<form action="fileupload.do" method="post" enctype="multipart/form-data"> file:<input type="file" name="file"/><br/> <input type="submit" value="submit"/> </form>
展示所有文件的页面
<c:forEach items="${files}" var="file"> <form action="downloadFile.do" method="post" > <label>${file.name}</label> <input type="submit" value="下载"/> <input type="hidden" name ="fileName" value="${file.name}"> </form> </c:forEach>
文件上传、展示、下载的控制类
package springapp.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.context.ServletContextAware; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; @Controller public class FileAction implements ServletContextAware { private ServletContext servletContext; /** * 单个文件上传 * * @param request * @param mrequest * @param response * @return * @throws IOException */ @RequestMapping(value = "fileupload.do", method = RequestMethod.POST) public String fileUpload(HttpServletRequest request, Model model, MultipartHttpServletRequest mrequest, HttpServletResponse response) throws IOException { MultipartFile file = mrequest.getFile("file"); String fileName = file.getOriginalFilename(); String path = this.servletContext.getRealPath("temp"); // System.out.println(path); String pathAndfileName = path + "\\" + fileName; // System.out.println(pathAndfileName); if (!file.isEmpty()) { this.copyFile(file.getInputStream(), pathAndfileName); return "redirect:showFile.do"; } model.addAttribute("msg", "上失败"); return "uploadFile"; } /** * 保存文件到本地 * * @param in * @param fileName * @throws IOException */ public void copyFile(InputStream in, String filePathAndName) throws IOException { FileOutputStream fos = new FileOutputStream(filePathAndName); byte[] buffer = new byte[1024 * 1024]; int bytesum = 0; int byteread = 0; while ((byteread = in.read(buffer)) != -1) { bytesum += byteread; fos.write(buffer, 0, byteread); fos.flush(); } fos.close(); in.close(); } public void setServletContext(ServletContext arg0) { // TODO Auto-generated method stub this.servletContext = arg0; } /** * 展示文件 * * @param model * @param request * @param response * @return */ @RequestMapping("showFile.do") public String showFile(Model model, HttpServletRequest request, HttpServletResponse response) { String fileAddress = this.servletContext.getRealPath("temp"); File[] files = new File(fileAddress).listFiles(); List<File> fileList = new ArrayList<File>(); for (File file : files) { fileList.add(file); } model.addAttribute("files", fileList); return "showFile"; } /** * 下载文件 * @param response * @param fileName * @throws IOException */ @RequestMapping(value = "downloadFile.do", method = RequestMethod.POST) public void downLoadFile(HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException { response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("gb2312"), "iso8859-1")); File file = new File(fileName); String path = this.servletContext.getRealPath("temp"); InputStream in = new FileInputStream(path + "\\" + file); OutputStream os = response.getOutputStream(); byte[] b = new byte[1024 * 1024]; int length; while ((length = in.read(b)) > 0) { os.write(b, 0, length); } in.close(); } }