SpringMVC文件上传

SpringMVC文件上传

核心API—DiskFileItemFactory

DiskFileItemFactory类:将请求消息实体中的每一个项目封装成单独的DiskFileItem (FileItem接口的实现) 对象的任务。当上传的文件项目比较小(10KB)时,直接保存在内存中(速度比较快),比较大时,以临时文件的形式,保存在磁盘临时文件夹。

方法

• public void setSizeThreshold(int sizeThreshold) :设置内存缓冲区的大小,默认值为10K。当上传文件大于缓冲区大小时,fileupload组件将使用临时文件缓存上传文件。

• public void setRepository(Java.io.File repository) :指定临时文件目录,默认值为System.getProperty(“java.io.tmpdir”).

• public DiskFileItemFactory(int sizeThreshold,java.io.File repository) :构造函数

ServletFileUpload 负责处理上传的文件数据,并将表单中每个输入项封装成一个FileItem 对象中。常用方法有:

• boolean isMultipartContent(HttpServletRequest request) :判断上传表单是否为multipart/form-data类型

• List parseRequest(HttpServletRequest request):解析request对象,并把表单中的每一个输入项包装成一个fileItem 对象,并返回一个保存了所有FileItem的list集合。

• setFileSizeMax(long fileSizeMax) :设置上传文件的最大值

• setSizeMax(long sizeMax) :设置上传文件总量的最大值

• setHeaderEncoding(java.lang.String encoding) :设置编码格式

• setProgressListener(ProgressListener pListener)

文件上传实现步骤

1、创建DiskFileItemFactory对象,设置缓冲区大小和临时文件目录

2、使用DiskFileItemFactory 对象创建ServletFileUpload对象,并设置上传文件的大小限制。

3、调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象。

4、对list进行迭代,每迭代一个FileItem对象,调用其isFormField方法判断是否是上传文件,若为上传文件,则通过.getName() 获取文件名,新建文件(可以给文件名添加时间戳防止上传相同文件时被覆盖)保存,文件较大时还要删除临时文件

Controller

package controller;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
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 org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * @author lei
 * @date 2020/5/11 8:57
 */
@Controller
public class FileController {
    /**
     * 传统方法上传文件
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/user")//访问地址
    public String fileUpload(HttpServletRequest request) throws Exception {
        System.out.println("文件上传。。。。");
        //使用fileupload组件上传
        //上传位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        File file = new File(path);
        if (!file.exists()) {
            //创建文件夹
            file.mkdirs();
        }
        //解析request ,获取上传文件
        //创建一个解析器工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
		//获得解析器对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        List<FileItem> items = fileUpload.parseRequest(request);
        //判断是否为表单类型
        for (FileItem item : items) {
            if (item.isFormField()) {
            } else {
                //说明上传文件项
                //获取文件名称
                String fieldName = item.getName();
                System.out.println(fieldName);
                item.write(new File(path, fieldName));
                //删除临时文件
                item.delete();
            }
        }
        return "suc";
    }
    /**
     * SringMVC上传文件
     *
     * @param request
     * @param upload
     * @return
     * @throws Exception
     */
    @RequestMapping("/user2")
    //MultipartFile upload 必须和页面文件name属性同名
    public String fileUpload2(HttpServletRequest request, MultipartFile upload) throws Exception {
        System.out.println("文件上传。。。。");
        //使用fileupload组件上传
        //上传位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        File file = new File(path);
        if (!file.exists()) {
            //创建文件夹
            file.mkdirs();
        }
        //解析request ,获取上传文件
        //说明上传文件项
        //获取文件名称
        String fieldName = upload.getOriginalFilename();
        String name = upload.getName();
        System.out.println("文件名" + fieldName + ", getName" + name);
        System.out.println(fieldName);
        upload.transferTo(new File(path, fieldName));
        return "suc";
    }
    /**
     * 跨服务器上传文件
     *
     * @param upload
     * @return
     * @throws Exception
     */
    @RequestMapping("/user3")
    //MultipartFile upload 必须和页面文件name属性同名
    public String fileUpload3(MultipartFile upload) throws Exception {
        System.out.println("文件上传。。。。");
        //解析request ,获取上传文件
        //说明上传文件项
        //获取文件名称
        String fieldName = upload.getOriginalFilename();
        String path = "http://localhost:9090/fileuploadServer_war_exploded/upload/";
		//使上传相同的文件时不会被覆盖 
		//String uuid = UUID.randomUUID().toString().replace("-", "");
		//fieldName += uuid;
        //创建客户端对象
        Client client = Client.create();
        //和图片服务器连接
        WebResource webResource = client.resource(path + fieldName);
        webResource.put(upload.getBytes());//通过字节数组传输数据
        return "suc";
    }
}

Spring配置

<?xml version="1.0" encoding="UTF-8"?>
<?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:mv="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--配置包扫描-->
    <context:component-scan base-package="controller"/>
     <!--配置注解驱动-->			
    <mv:annotation-driven/>
    <mv:default-servlet-handler/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <!--    文件所在目录-->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
          <!--    文件名后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>
<!--    配置文件解析器-->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
     id="multipartResolver">
        <property name="maxInMemorySize" value="110485760"/>
    </bean>
</beans>

页面

<%--
  Created by IntelliJ IDEA.
  User: xiaolei
  Date: 2020/5/11
  Time: 8:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <!--必须设置: enctype="multipart/form-data" <input type="file" name="file"> 必须设置name属性-->
  <form method="post" action="${pageContext.request.contextPath}/user" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
  </form>
  <form method="post" action="${pageContext.request.contextPath}/user2" enctype="multipart/form-data">
    <input type="file" name="upload">
    <input type="submit" value="springmvc上传">
  </form>
  <form method="post" action="${pageContext.request.contextPath}/user3" enctype="multipart/form-data">
    <input type="file" name="upload">
    <input type="submit" value="跨服务器上传">
  </form>
  </body>
</html>

Web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
         <!--设置过滤器解决乱码-->
    <filter>
        <filter-name>encodeFilter</filter-name>
        <filter-class>filter.EncodeFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>encodeFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:beans.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值