当前位置: 移动技术网 > IT编程>开发语言>Java > Spring boot实现文件上传实例(多文件上传)

Spring boot实现文件上传实例(多文件上传)

2019年07月22日  | 移动技术网IT编程  | 我要评论
文件上传主要分以下几个步骤: (1)新建maven java project; (2)在pom.xml加入相应依赖; (3)新建一个表单页面(这里使用th

文件上传主要分以下几个步骤:

(1)新建maven java project;

(2)在pom.xml加入相应依赖;

(3)新建一个表单页面(这里使用thymleaf);

(4)编写controller;

(5)测试;

(6)对上传的文件做一些限制;

(7)多文件上传实现

(1)新建maven java project

新建一个名称为spring-boot-fileupload maven java项目;

(2)在pom.xml加入相应依赖;

加入相应的maven依赖,具体看以下解释:

<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
 <modelversion>4.0.0</modelversion> 
 <groupid>com.example</groupid> 
 <artifactid>spring-boot-fileupload</artifactid> 
 <version>0.0.1-snapshot</version> 
  
 <!-- 
    spring boot 父节点依赖, 
        引入这个之后相关的引入就不需要添加version配置, 
    spring boot会自动选择最合适的版本进行添加。 
   --> 
  <parent> 
    <groupid>org.springframework.boot</groupid> 
    <artifactid>spring-boot-starter-parent</artifactid> 
    <version>1.4.0.release</version> 
  </parent> 
 
 <dependencies> 
    <!-- spring boot web支持:mvc,aop... --> 
    <dependency> 
      <groupid>org.springframework.boot</groupid> 
      <artifactid>spring-boot-starter-web</artifactid> 
    </dependency> 
 
    <!-- thmleaf模板依赖. --> 
    <dependency> 
     <groupid>org.springframework.boot</groupid> 
     <artifactid>spring-boot-starter-thymeleaf</artifactid> 
    </dependency> 
 </dependencies> 
 
  <build> 
    <plugins> 
      <!-- 编译版本; --> 
      <plugin> 
       <artifactid>maven-compiler-plugin</artifactid> 
       <configuration> 
         <source>1.7</source> 
         <target>1.7</target> 
       </configuration> 
      </plugin> 
    </plugins> 
  </build> 
</project> 

(3)新建一个表单页面(这里使用thymleaf)

在src/main/resouces新建templates,在templates下新建一个file.html:

<!doctype html> 
<html xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:th="http://www.thymeleaf.org" 
  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> 
<head> 
<title>hello world!</title> 
</head> 
<body> 
  <form method="post" enctype="multipart/form-data" action="/upload"> 
    <p> 
      文件:<input type="file" name="file" /> 
    </p> 
    <p> 
      <input type="submit" value="上传" /> 
    </p> 
  </form> 
</body> 
</html> 

(4)编写controller;

编写controller进行测试,这里主要实现两个方法:其一就是提供访问的/file路径;其二就是提供post上传的/upload方法,具体看代码实现:

@controller 
public class fileuploadcontroller { 
  // 访问路径为:http://127.0.0.1:8080/file 
  @requestmapping("/file") 
  public string file() { 
    return "/file"; 
  } 
 
  /** 
   * 文件上传具体实现方法; 
   *  
   * @param file 
   * @return 
   */ 
  @requestmapping("/upload") 
  @responsebody 
  public string handlefileupload(@requestparam("file") multipartfile file) { 
    if (!file.isempty()) { 
      try { 
        /* 
         * 这段代码执行完毕之后,图片上传到了工程的跟路径; 大家自己扩散下思维,如果我们想把图片上传到 
         * d:/files大家是否能实现呢? 等等; 
         * 这里只是简单一个例子,请自行参考,融入到实际中可能需要大家自己做一些思考,比如: 1、文件路径; 2、文件名; 
         * 3、文件格式; 4、文件大小的限制; 
         */ 
 
        bufferedoutputstream out = new bufferedoutputstream( 
            new fileoutputstream(new file( 
                file.getoriginalfilename()))); 
        out.write(file.getbytes()); 
        out.flush(); 
        out.close(); 
 
      } catch (filenotfoundexception e) { 
        e.printstacktrace(); 
        return "上传失败," + e.getmessage(); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
        return "上传失败," + e.getmessage(); 
      } 
 
      return "上传成功"; 
 
    } else { 
      return "上传失败,因为文件是空的."; 
    } 
  } 
   
  // 访问路径为:http://127.0.0.1:8080/file 
    @requestmapping("/mutifile") 
    public string mutifile() { 
      return "/mutifile"; 
    } 

(5)编写application.java然后测试

application没什么代码,就是spring boot的启动配置,具体如下:

package com.example.controller; 
 
import javax.servlet.multipartconfigelement; 
 
import org.springframework.boot.springapplication; 
import org.springframework.boot.autoconfigure.springbootapplication; 
//import org.springframework.boot.context.embedded.multipartconfigfactory; 
import org.springframework.boot.web.servlet.multipartconfigfactory; 
import org.springframework.context.annotation.bean; 
 
@springbootapplication 
public class application { 
  public static void main(string[] args) { 
     springapplication.run(application.class, args); 
  } 
   
} 

然后你就可以访问:http://127.0.0.1:8080/file 进行测试了,文件上传的路径是在工程的跟路径下,请刷新查看,其它的请查看代码中的注释进行自行思考

(6)对上传的文件做一些限制; 

对文件做一些限制是有必要的,在application.java进行编码配置:。 

@bean  
  public multipartconfigelement multipartconfigelement() {  
      multipartconfigfactory factory = new multipartconfigfactory(); 
      //// 设置文件大小限制 ,超了,页面会抛出异常信息,这时候就需要进行异常信息的处理了; 
      factory.setmaxfilesize("128kb"); //kb,mb 
      /// 设置总上传数据总大小 
      factory.setmaxrequestsize("256kb");  
      //sets the directory location where files will be stored. 
      //factory.setlocation("路径地址"); 
      return factory.createmultipartconfig();  
  } 

(7)多文件上传实现

多文件对于前段页面比较简单,具体代码实现:

在src/resouces/templates/mutifile.html

<!doctype html> 
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" 
   xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> 
  <head> 
    <title>hello world!</title> 
  </head> 
  <body> 
    <form method="post" enctype="multipart/form-data" action="/batch/upload">  
      <p>文件1:<input type="file" name="file" /></p> 
      <p>文件2:<input type="file" name="file" /></p> 
      <p>文件3:<input type="file" name="file" /></p> 
      <p><input type="submit" value="上传" /></p> 
    </form> 
  </body> 
</html>  

fileuploadcontroller中新增两个方法:

// 访问路径为:http://127.0.0.1:8080/mutifile 
    @requestmapping("/mutifile") 
    public string mutifile() { 
      return "/mutifile"; 
    } 
 
  /** 
   * 多文件具体上传时间,主要是使用了multiparthttpservletrequest和multipartfile 
   *  
   * @param request 
   * @return 
   */ 
 
  @requestmapping(value = "/batch/upload", method = requestmethod.post) 
  @responsebody 
  public string handlefileupload(httpservletrequest request) { 
    list<multipartfile> files = ((multiparthttpservletrequest) request) 
        .getfiles("file"); 
    multipartfile file = null; 
    bufferedoutputstream stream = null; 
    for (int i = 0; i < files.size(); ++i) { 
      file = files.get(i); 
      if (!file.isempty()) { 
        try { 
          byte[] bytes = file.getbytes(); 
          stream = new bufferedoutputstream(new fileoutputstream( 
              new file(file.getoriginalfilename()))); 
          stream.write(bytes); 
          stream.close(); 
 
        } catch (exception e) { 
          stream = null; 
          return "you failed to upload " + i + " => " 
              + e.getmessage(); 
 
        } 
      } else { 
        return "you failed to upload " + i 
            + " because the file was empty."; 
      } 
 
    } 
    return "upload successful"; 
 
  } 

访问路径:http://127.0.0.1:8080/mutifile 进行测试。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网