原生态文件上传VSSpringMvc文件上传
首先实现这个文件上传需要导入两个jar包:
或者是引入maven依赖:
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
原生态文件上传:
这里话不多说,直接上代码:
UploadController:
package com.controller; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.List; import java.util.UUID; /** * @program: _20191123SSM->UploadController * @description: 文件上传处理器 * @author: 安生 * @create: 2019-11-27 08:32 **/ @Controller @RequestMapping("/UploadController") public class UploadController { @RequestMapping("/upload01") public String upload01(HttpServletRequest request) throws Exception { System.out.println("文件上传...."); //通过fileupload组件实现文件上传 //标记保存的路径 String realPath = request.getSession().getServletContext().getRealPath("/upload/"); //判断该路径是否存在 File file = new File(realPath); if(!file.exists()){ file.mkdirs(); } //解析request DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); List<FileItem> fileItems = servletFileUpload.parseRequest(request); //遍历 for (FileItem fileItem : fileItems) { //判断是否是文件项 if(fileItem.isFormField()){ //为普通项 }else{ //文件项 //获取文件名 String fileItemName = fileItem.getName(); //扩展: //确保文件名的唯一性 可以使用UUID String replace = UUID.randomUUID().toString().replace("-", ""); fileItemName = replace+"_"+fileItemName; System.out.println(fileItemName); //获取路径: String path = realPath+fileItemName; System.out.println(path); //完成文件上传 fileItem.write(new File(realPath,fileItemName)); //清理文件 fileItem.delete(); } } return "success"; } }
Jsp页面:
<%-- Created by IntelliJ IDEA. User: admin Date: 2019/11/27 Time: 8:31 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件上传</title> </head> <body> <h3>传统的文件上传</h3> <form action="UploadController/upload01" method="post" enctype="multipart/form-data"> <input type="file" name="upload"/> <input type="submit" value="提交"/> </form> </body> </html>
Springmvc.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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-4.3.xsd"> <!--SpringMVC的配置文件,包含网站跳转逻辑的控制,配置 --> <context:component-scan base-package="com.controller"></context:component-scan> <!--配置视图解析器,方便页面返回 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--两个标准配置 --> <!-- 将springmvc不能处理的请求交给tomcat --> <mvc:default-servlet-handler /> <!-- 能支持springmvc更高级的一些功能,JSR303校验,快捷的ajax...映射动态请求 --> <mvc:annotation-driven /> </beans>
web.xml
<!--2、springmvc的前端控制器,拦截所有请求 --> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 此处不指定的话,需要把这个配置文件放在web.xml的统计目录--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 3、字符编码过滤器,一定要放在所有过滤器之前 --> <filter> <filter-name>CharacterEncodingFilter</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>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
成功:
使用SpringMvc实现文件上传:
Controller:
@RequestMapping("/upload02") public String upload02(HttpServletRequest request, MultipartFile upload) throws Exception { System.out.println("SpringMvc实现文件上传"); //标记保存路径 String realPath = request.getSession().getServletContext().getRealPath("/upload2/"); //判断该路径是否存在 File file = new File(realPath); if(!file.exists()){ file.mkdirs(); } //获取文件名 String originalFilename = upload.getOriginalFilename(); //完成文件上传 upload.transferTo(new File(realPath,originalFilename)); return "success"; }
web.xml不变
springMvc.xml
添加上文件解析器
<!-- 配置文件解析器 把request解析成upload返回回去--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- defaultEncoding:请求的编码格式必须和用户JSP的编码一致,以便正确读取表单中的内容。 uploadTempDir:文件上传过程中的临时目录,上传完成后,临时文件会自动删除 maxUploadSize:设置文件上传大小上限(单位为字节)-1为无限制 --> <property name="defaultEncoding" value="UTF-8" /> <property name="maxUploadSize" value="102400000" /> <!-- uploadTempDir可以不做设置,有默认的路径,上传完毕会临时文件会自动被清理掉 --> <!-- <property name="uploadTempDir" value="/upload/"></property>--> </bean>
<h3>Spring的文件上传</h3> <form action="UploadController/upload02" method="post" enctype="multipart/form-data"> <input type="file" name="upload"/> <input type="submit" value="提交"/> </form>
成功:
注意:
1、SpringMvc的form表单提交方式
method="post" enctype="multipart/form-data"
还有表单中的input type = file name=upload;
要记得写name属性在Controller会用到
2、SpringMvc的配置文件解析器时的bean id必须是
multipartResolver
3、UploadController的upload2方法
public String upload02(HttpServletRequest request, MultipartFile upload) throws Exception
这里的MultipartFie 后面的名字要与jsp页面的那个input type = file name = upload; 那个name属性的值一样