springMVC上传文件(三种方法)

                       

在基于springmvc的web开发过程中,上传文件功能是经常遇到的,下面开总结一下springmvc上传文件的一些要点吧!
首先,在springmvc配置文件中配置上传文件的bean
spring-servlet.xml文件中

<!-- 上传文件的配置 -->    <bean id="multipartResolver"        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <property name="maxUploadSize">            <value>10000000</value>        </property>        <property name="defaultEncoding">            <value>UTF-8</value>        </property>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

前台jsp代码,采用表单提交的方式来上传文件,上传文件的表单和其他表单不一样的地方是表单的enctype必须是enctype=”multipart/form-data”

<%@ 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><form name="serForm" action="/SpringMVC006/fileUpload" method="post"  enctype="multipart/form-data"><h1>采用流的方式上传文件</h1><input type="file" name="file"><input type="submit" value="upload"/></form><form name="Form2" action="/SpringMVC006/fileUpload2" method="post"  enctype="multipart/form-data"><h1>采用multipart提供的file.transfer方法上传文件</h1><input type="file" name="file"><input type="submit" value="upload"/></form><form name="Form2" action="/SpringMVC006/springUpload" method="post"  enctype="multipart/form-data"><h1>使用spring mvc提供的类的方法上传文件</h1><input type="file" name="file"><input type="submit" value="upload"/></form></body></html>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

后台controller代码其实很简单,在springmvc中上传的文件不是File,而是MultipartFile这个类,
如何将MultipartFile转为File呢?下面代码做出解释

private File saveFile(HttpServletRequest request, MultipartFile file) {        // 判断文件是否为空        if (!file.isEmpty()) {            try {                // 保存的文件路径(如果用的是Tomcat服务器,文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中  )                String filePath = request.getSession().getServletContext()                        .getRealPath("/") + "upload/" + file.getOriginalFilename();                File saveDir = new File(filePath);                if (!saveDir.getParentFile().exists())                    saveDir.getParentFile().mkdirs();                // 转存文件                file.transferTo(saveDir);                return saveDir;            } catch (Exception e) {                e.printStackTrace();            }        }        return null;    }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

这个方法返回的一个File实体,然后就可以对这个文件进行操作了比如读取这个文件里面的内容之类的,这就关系到java 中的IO操作了,这里就不解释了,关于Java中的IO操作,小伙伴们可以看看我的另一篇博客,
Java IO for android
下面就来看看springmvc如何获取文件的方法吧!
第一种方式

*     * 通过流的方式上传文件     * @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象     */    @RequestMapping("fileUpload")    public String  fileUpload(@RequestParam("file") 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 (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        long  endTime=System.currentTimeMillis();        System.out.println("方法一的运行时间:"+String.valueOf(endTime-startTime)+"ms");        return "/success";     }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

第二种方式

/*     * 采用file.Transto 来保存上传的文件     */    @RequestMapping("fileUpload2")    public String  fileUpload2(@RequestParam("file") 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";     }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

第三种方式

/*     *采用spring提供的上传文件的方法     */    @RequestMapping("springUpload")    public String  springUpload(HttpServletRequest request) throws IllegalStateException, IOException    {         long  startTime=System.currentTimeMillis();         //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)        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";     }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

性能比较
第一次我用一个4M的文件:

fileName:test.rar
方法一的运行时间:14712ms
fileName:test.rar
方法二的运行时间:5ms
方法三的运行时间:4ms

第二次:我用一个50M的文件
方式一进度很慢,估计得要个5分钟

方法二的运行时间:67ms
方法三的运行时间:80ms

从测试结果我们可以看到:用springMVC自带的上传文件的方法要快的多!

对于测试二的结果:可能是方法三得挨个搜索,所以要慢点。不过一般情况下我们是方法三,因为他能提供给我们更多的方法

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/qq_43746757/article/details/86467894