当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot实现文件上传示例代码

Spring Boot实现文件上传示例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

使用springboot进行文件上传的方法和springmvc差不多,本文单独新建一个最简单的demo来说明一下。

主要步骤包括:

1、创建一个springboot项目工程,本例名称(demo-uploadfile)。

2、配置 pom.xml 依赖。

3、创建和编写文件上传的 controller(包含单文件上传和多文件上传)。

4、创建和编写文件上传的 html 测试页面。

5、文件上传相关限制的配置(可选)。

6、运行测试。

项目工程截图如下:

文件代码:

  <dependencies>

    <!-- spring boot web支持 -->
    <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>

    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-test</artifactid>
      <scope>test</scope>
    </dependency>
  </dependencies>
package com.example.controller;

import java.io.bufferedoutputstream;
import java.io.file;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.util.list;

import javax.servlet.http.httpservletrequest;

import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.multipart.multiparthttpservletrequest;

/**
 * 文件上传的controller
 * 
 * @author 单红宇(csdn catoop)
 * @create 2017年3月11日
 */
@controller
public class fileuploadcontroller {

  // 访问路径为:http://ip:port/upload
  @requestmapping(value = "/upload", method = requestmethod.get)
  public string upload() {
    return "/fileupload";
  }

  // 访问路径为:http://ip:port/upload/batch
  @requestmapping(value = "/upload/batch", method = requestmethod.get)
  public string batchupload() {
    return "/mutifileupload";
  }

  /**
   * 文件上传具体实现方法(单文件上传)
   *
   * @param file
   * @return
   * 
   * @author 单红宇(csdn catoop)
   * @create 2017年3月11日
   */
  @requestmapping(value = "/upload", method = requestmethod.post)
  @responsebody
  public string upload(@requestparam("file") multipartfile file) {
    if (!file.isempty()) {
      try {
        // 这里只是简单例子,文件直接输出到项目路径下。
        // 实际项目中,文件需要输出到指定位置,需要在增加代码处理。
        // 还有关于文件格式限制、文件大小限制,详见:中配置。
        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 "上传失败,因为文件是空的.";
    }
  }

  /**
   * 多文件上传 主要是使用了multiparthttpservletrequest和multipartfile
   *
   * @param request
   * @return
   * 
   * @author 单红宇(csdn catoop)
   * @create 2017年3月11日
   */
  @requestmapping(value = "/upload/batch", method = requestmethod.post)
  public @responsebody string batchupload(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";
  }
}

package com.example.configuration;

import javax.servlet.multipartconfigelement;

import org.springframework.boot.web.servlet.multipartconfigfactory;
import org.springframework.context.annotation.bean;

/**
 * 文件上传配置
 * 
 * @author 单红宇(csdn catoop)
 * @create 2017年3月11日
 */
public class fileuploadconfiguration {

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

@springbootapplication
public class demouploadfileapplication {

  public static void main(string[] args) {
    springapplication.run(demouploadfileapplication.class, args);
  }
}
<!doctype html>
<html>
<head>
<title>文件上传示例</title>
</head>
<body>
  <h2>文件上传示例</h2>
  <hr/>
  <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>
<!doctype html>
<html>
<head>
<title>批量文件上传示例</title>
</head>
<body>
  <h2>批量文件上传示例</h2>
  <hr/>
  <form method="post" enctype="multipart/form-data"
    action="/upload/batch">
    <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>

最后启动服务,访问 http://localhost:8080/upload 和 http://localhost:8080/upload/batch 测试文件上传。

demo源代码下载地址:

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网