服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring MVC 文件上传的示例代码

Spring MVC 文件上传的示例代码

2021-01-09 14:43yuanfy008 Java教程

本篇文章主要介绍了Spring MVC 文件上传的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

一如既往记录下常用而又容易忘记的东西,本篇博文主要针对spring mvc是如何上传文件的。以下记录两种上传方法并针对案例进行记录。(有关spring mvc其他配置省略)

1、使用spring mvc 上传文件必须配置文件解析器,如下:

?
1
2
3
4
5
6
<!-- 上传文件拦截,设置最大上传文件大小 10m=10*1024*1024(b)=10485760 bytes -->
 <bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver">
  <property name="maxuploadsize" value="10485760" />
  <property name="maxinmemorysize" value="10240000" />
  <property name="defaultencoding" value="utf-8" />
 </bean>

2、建立上传文件表单代码,其中要注意form表单中的enctype 属性,必须存在且必须为multipart/form-data。还有当form中存在button标签时,用ajax异步提交表单后,也面会被刷新。原因:button 存在时会再次提交一下表单,所以页面被刷新了。

?
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
<!--
  enctype 属性值:
    1、application/x-www-form-urlencoded 在发送前编码所有字符(默认)
    2、multipart/form-data 不对字符编码。 在使用包含文件上传控件的表单时,必须使用该值。
    3、text/plain 空格转换为 "+" 加号,但不对特殊字符编码。
-->
<div class="row">
  <form method="post" enctype="multipart/form-data" id="form1">
    <div><label>1、采用流的方式</label></div>
    <div class="col-sm-7" style="padding-left:0px">
      <div class="input-group">
        <input type="text" class="form-control" id="showfileinput1">
        <input type="file" style="display:none" name="txtfile" id="uploadfileinput1" accept="text/plain">
        <span class="input-group-addon" id="uploadfilebutton1">
          <span class="glyphicon glyphicon-folder-open"></span>
          <label>浏览</label>
        </span>
      </div>
    </div>
    <div class="col-sm-5">
      <!--
                  当form中存在button标签时,用ajax异步提交表单后,也面会被刷新。(感觉很诡异)
                  原因:button 存在时会再次提交一下表单,所以页面被刷新了。(之前认为button type='submit' 时)button才有提交表单的功能。
      -->
      <a class="btn btn-default" id="submit1">上传</a>
    </div>
  </form>
</div>

 3.1、使用commonsmultipartfile接收上传文件,其中要注意的是:方法中commonsmultipartfile对应的变量名如果不是对应表单中文件输入框<input type="file" style="display:none" name="txtfile" id="uploadfileinput1" accept="text/plain">的名称就必须加上@requestparam("txtfile") 强制注入。

?
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
/**
  * @description: 通过文件流的形式上传
  * @param file  @requestparam("txtfile") 将name=txtfile控件得到的文件封装成commonsmultipartfile对象,
  *       如果不这样做会报commonsmultipartfile没有初始化的错误
  *       java.lang.nosuchmethodexception: org.springframework.web.multipart.commons.commonsmultipartfile.<init>()
  * @return
  * @author yuanfy
  * @date 2017年9月15日 下午4:36:11
  * @version 6.5
  */
 @requestmapping(value="test/upload1")
 @responsebody
 public string testupload1(@requestparam("txtfile")commonsmultipartfile file){
   long times = system.currenttimemillis();
   if (file == null) {
     return null;
   }
   stringbuilder filecontent = new stringbuilder();
   //1、获取文件信息
   fileutils.getfileinfo(file, filecontent);
   
   //2、上传文件并获取文件内容
   try {
     file.transferto(new file("f:\\text.log"));//另存文件
     filecontent.append(fileutils.getfilecontentbyline(file.getinputstream()));
   }
   catch (ioexception e) {
     return "获取文件内容失败";
   }
   
   //3、返回文件信息和内容
   string content = filecontent.tostring();
   content = content.replace("times", (system.currenttimemillis()-times) + "ms");
   return content;
 }

  界面效果图如下:

Spring MVC 文件上传的示例代码

3.2、使用commonsmultipartresolver获取存放文件对象,拿到文件对象后遍历每个文件上传及获取相关的内容。

?
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
@requestmapping(value="test/upload2")
  @responsebody
  public string testupload2(httpservletrequest request){
    long times = system.currenttimemillis();
    stringbuilder filecontent = new stringbuilder();
    //1.根据servletcontext获取多文件上传解析组件
    commonsmultipartresolver multipartresolver = new commonsmultipartresolver(request.getsession().getservletcontext());
    if (!multipartresolver.ismultipart(request)) {
      return "不是上传文件表单,请检查表单属性";
    }
    //2.将请求对象转换为多文件请求对象。
    multiparthttpservletrequest multiparthttpservletrequest = (multiparthttpservletrequest) request;
    //3、根据多文件请求对象获取文件存放map
    map<string, multipartfile> filemap = multiparthttpservletrequest.getfilemap();
    iterator<entry<string, multipartfile>> iterator = filemap.entryset().iterator();
    //4、迭代文件map,获取具体的multipartfile
    while (iterator.hasnext()) {
      entry<string, multipartfile> entry = iterator.next();
      multipartfile multipartfile = entry.getvalue();
      //获取文件头信息
      fileutils.getfileinfo(multipartfile, filecontent);
      try {
        //上传文件
        multipartfile.transferto(new file("f:\\text.log"));
        //获取文件内容
        filecontent.append(fileutils.getfilecontentbyline(multipartfile.getinputstream()));
      }catch (exception e) {
        // todo auto-generated catch block
        e.printstacktrace();
      }
    }
    //5、返回文件信息和内容
    string content = filecontent.tostring();
    content = content.replace("times", (system.currenttimemillis()-times) + "ms");
    return content;
  }

其中第一步获取文件解析器对象应该都清楚只要在容器中配置了对应的对象我们就可以获取到它,而它有根据上下文获取的构造函数就方便多了。

?
1
2
3
4
5
6
7
8
9
/**
   * constructor for standalone usage. determines the servlet container's
   * temporary directory via the given servletcontext.
   * @param servletcontext the servletcontext to use
   */
  public commonsmultipartresolver(servletcontext servletcontext) {
    this();
    setservletcontext(servletcontext);
  }

然后根据request判断是否还有上传文件的表单,如果不是肯定直接返回,我们看看源码中是怎么判断的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//commonsmultipartresolver.class 主要判断request是否为空
@override
public boolean ismultipart(httpservletrequest request) {
  return (request != null && servletfileupload.ismultipartcontent(request));
//servletfileupload 主要判断是否是post方法,因为上传文件必须是post提交,其实我们可以在我们自定义controller中的方法指定访问
public static final boolean ismultipartcontent(httpservletrequest request) {
  if (!post_method.equalsignorecase(request.getmethod())) {
      return false;
    }
    return fileuploadbase.ismultipartcontent(new servletrequestcontext(request));
}
//fileuploadbase.class 如果请求是multipart 则返回true
public static final boolean ismultipartcontent(requestcontext ctx) {
    string contenttype = ctx.getcontenttype();//类似:multipart/form-data; boundary=----webkitformboundarylf3em94ldb0ocqxt
    if (contenttype == null) {
      return false;
    }
    if (contenttype.tolowercase(locale.english).startswith(multipart)) {
      return true;
    }
    return false;
}

所以如果request是上传文件的请求对象,则进行第二步。将request转换成多文件请求对象,然后获取存放文件的map。

可想而知这种方法效率是比第一种要低的,因为他要遍历文件map,但是在spring mvc常用的却是这种方法。

效果图如下:

Spring MVC 文件上传的示例代码

其中fileutils.java代码如下:

?
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.yuanfy.monitorsite.common.util;
 
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.io.inputstream;
 
import org.springframework.web.multipart.multipartfile;
 
/**
 * @description: 文件工具类方法
 * @author yuanfy
 * @date 2017年9月15日 下午2:45:40
 * @version 1.0
 */
public class fileutils {
  /**
   * @description: 获取文件信息
   * @param file commonsmultipartfile类型的文件
   * @param filecontent stringbuilder,封装文件信息
   * @author yuanfy
   * @date 2017年9月15日 下午2:51:34
   * @version 1.0
   */
  public static void getfileinfo(multipartfile file, stringbuilder filecontent) {
    filecontent.append("文件名称:\t\t").append(file.getname()).append("\n")
      .append("文件原始名称:\t").append(file.getoriginalfilename()).append("\n")
      .append("文件大小:\t\t").append(file.getsize()).append("\n")
      .append("文件类型:\t\t").append(file.getcontenttype()).append("\n")
      .append("读取文件时长:\t times").append("\n");
  }
  
  /**
   * @description: 根据文件对象获取文件内容
   * @param file
   * @author yuanfy
   * @date 2017年9月15日 下午5:01:57
   * @version 1.0
   * @throws ioexception
   * @throws filenotfoundexception
   */
  public static string getfilecontentbyline(file file) throws filenotfoundexception, ioexception {
    return getfilecontentbyline(new fileinputstream(file));
  }
  /**
   * @description: 根据文件输入流对象获取文件内容
   * @param in 文件输入流对象
   * @author yuanfy
   * @date 2017年9月15日 下午5:01:57
   * @version 1.0
   * @throws ioexception
   */
  public static string getfilecontentbyline(inputstream in) throws ioexception {
    stringbuilder filecontent = new stringbuilder();
    
    byte[] bytes = new byte[1024];
    int len = 0;
    while ((len = in.read(bytes)) != -1) {
      string content = new string(bytes, 0, len, "utf-8");
      filecontent.append(content);
    }
    streamutils.close(in);
    return filecontent.tostring();
  }
}

当然要想查看整个代码,可以访问我项目的整个代码:https://github.com/yuanfy/blog_demo

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/yuanfy008/p/7587151.html?utm_source=tuicool&utm_medium=referral

延伸 · 阅读

精彩推荐