SpringMVC上传文件的三种方法

yang-pig| 阅读:611 发表时间:2018-06-28 22:25:17 Java

我是在已经搭建好的springMVC环境下,maven工程中的pom.xml所需要的jar包(其中spring上传文件的两个主要jar:commons-fileupload.jar和commons-io.jar):

    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->

    <dependency>

      <groupId>commons-fileupload</groupId>

      <artifactId>commons-fileupload</artifactId>

      <version>1.3.2</version>

    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->

    <dependency>

      <groupId>commons-io</groupId>

      <artifactId>commons-io</artifactId>

      <version>2.4</version>

    </dependency>

在spring-mvc.xml中添加代码:

<!-- springMVC上传文件时,需要配置MultipartResolver处理器 -->

    <bean id="multipartResolver" 

        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <property name="defaultEncoding" value="utf-8"></property>

        <property name="maxUploadSize" value="10485760000"></property>

        <property name="maxInMemorySize" value="40960"></property>

    </bean>

前端页面(fileUpload.jsp)和上传成功返回页面(success.jsp):


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>springmvc-文件上传</title>

</head>

<body>

    <h1>采用流的方式上传文件</h1>

    <form name="form1" action="<c:url value='/fileUpload/upload_01'/>" method="post" enctype="multipart/form-data">

        <input type="file" name="file_01"/>

        <input type="submit" value="fileupload"/>

    </form>

    <br>

    <h1>采用multipart提供的file.transfer方法上传文件1</h1>

    <form name="form2" action="<c:url value='/fileUpload/upload_02'/>" method="post" enctype="multipart/form-data">

        <input type="file" name="file_02"/>

        <input type="submit" value="fileupload"/>

    </form>

    <br>

    <h1>采用multipart提供的file.transfer方法上传文件2</h1>

    <form name="form2" action="<c:url value='/fileUpload/upload_03'/>" method="post" enctype="multipart/form-data">

        <input type="file" name="file_03"/>

        <input type="submit" value="fileupload"/>

    </form>
    <br>
    <h1>使用spring MVC提供的方法上传文件</h1>

    <form name="form2" action="<c:url value='/fileUpload/upload_spring'/>" method="post" enctype="multipart/form-data">

        <input type="file" name="file_03"/>

        <input type="submit" value="fileupload"/>

    </form>

</body>

</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

    <h2>文件上传成功!</h2>

</body>

</html>

controller 的代码:



package com.ssmtest.controller.admin;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

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.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;

import java.io.*;

import java.util.Date;

import java.util.Iterator;


    @Controller
    @RequestMapping("/fileUpload")
    public class FileUploadController {

        @RequestMapping("/index")
        public String index()throws IOException {

            return "fileUpload";
        }


        /**
         * 通过流的方式上传文件
         * @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
         * <请替换成功能描述> <br>
         * <请替换成详细描述>
         * @param file
         * @return
         * @author caizh
         * @since [1.0.0]
         * @version [1.0.0,2017年2月5日]
         */
        @RequestMapping("/upload_01")
        public String fileUpload_1(@RequestParam("file_01")CommonsMultipartFile file)throws IOException {
            //用来检测程序运行时间
            long startTime = System.currentTimeMillis();
            System.out.println("fileName:"+file.getOriginalFilename());

            try{
                //获取输出流
                OutputStream os = new FileOutputStream("E:/"+new Date().getTime()+file.getOriginalFilename());
                //获取输入流CommonsMultipartFile中可以直接得到文件的流
                InputStream is = file.getInputStream();
                int temp;
                //一个一个字节的读取并写入
                while((temp=is.read())!=(-1)){
                    os.write(temp);
                }
                os.flush();
                os.close();
                is.close();
            }catch(Exception e){
                e.printStackTrace();
            }
            long endTime = System.currentTimeMillis();
            System.out.println("方法一的运行时间:"+String.valueOf(endTime-startTime)+"ms");
            return "success";
        }

        /**
         * 采用file.Transto 来保存上传的文件
         * <请替换成功能描述> <br>
         * <请替换成详细描述>
         * @param file
         * @return
         * @throws IOException
         * @author caizh
         * @since [1.0.0]
         * @version [1.0.0,2017年2月5日]
         */
        @RequestMapping("/upload_02")
        public String fileUpload_2(@RequestParam("file_02") CommonsMultipartFile file)throws IOException {
            long startTime = System.currentTimeMillis();
            System.out.println("fileName:"+file.getOriginalFilename());
            String path = "E:/"+new Date().getTime()+file.getOriginalFilename();

            File newFile = new File(path);
            //通过CommonsMultipartFile 的方法直接写文件
            file.transferTo(newFile);
            long endTime = System.currentTimeMillis();
            System.out.println("方法二的运行时间:"+String.valueOf(endTime-startTime)+"ms");
            return "success";
        }

        /**
         * 使用MultipartFile上传文件
         * <请替换成功能描述> <br>
         * <请替换成详细描述>
         * @param file
         * @return
         * @author caizh
         * @since [1.0.0]
         * @version [1.0.0,2017年2月5日]
         */
        @RequestMapping("/upload_03")
        public String fileUpload_3(@RequestParam(value="file_03",required=false)MultipartFile file,
                                   HttpServletRequest request){
            String path = request.getSession().getServletContext().getRealPath("upload");
            System.out.println(path);
            String fileName = file.getOriginalFilename();
            File targetFile = new File(path,fileName);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            //保存
            try {
                file.transferTo(targetFile);
            }catch(Exception e){
                e.printStackTrace();
            }
            return "success";
        }

        /**
         * 采用spring提供的上传文件的方法
         * <请替换成功能描述> <br>
         * <请替换成详细描述>
         * @param request
         * @return
         * @throws IllegalStateException
         * @throws IOException
         * @author caizh
         * @since [1.0.0]
         * @version [1.0.0,2017年2月5日]
         */
        @RequestMapping("/upload_spring")
        public String springUpload(HttpServletRequest request)throws IllegalStateException, IOException{
            long startTime = System.currentTimeMillis();
            //将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)

            String t = request.getParameter("test");

            System.out.println("test:"+t);

            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //检查form中是否有enctype="multipart/form-data"
            if(multipartResolver.isMultipart(request))
            {
                //将request变成多request

                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest中所有的文件名

                Iterator iter = multiRequest.getFileNames();

                while(iter.hasNext()){
                    //一次遍历所有的文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if(file!=null){
                        String path = "E:/springUpload"+file.getOriginalFilename();
                        //上传
                        file.transferTo(new File(path));
                    }
                }
            }
            long endTime = System.currentTimeMillis();
            System.out.println("方法三的运行时间:"+String.valueOf(endTime-startTime)+"ms");
            return "success";
        }

    }

好了,全部代码都给出了,博主是测试成功了,感兴趣的朋友可以去比较不同上传方式的效率!