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

 更新时间:2017年03月22日 09:39:45   作者:catoop  
本篇文章主要介绍了Spring Boot实现文件上传示例代码,可以实现单文件和多文件的上传,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

使用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源代码下载地址:uploadfile_jb51.rar

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

相关文章

  • java线程之死锁

    java线程之死锁

    这篇文章主要介绍了Java线程之死锁,死锁是这样一种情形-多个线程同时被阻塞,它们中的一个或者全部都在等待某个资源被释放。由于线程被无限期地阻塞,因此程序不可能正常终止
    2022-05-05
  • Spring事件监听机制使用和原理解析

    Spring事件监听机制使用和原理解析

    Spring的监听机制基于观察者模式,就是就是我们所说的发布订阅模式,这种模式可以在一定程度上实现代码的解耦,本文将从原理上解析Spring事件监听机制,需要的朋友可以参考下
    2023-06-06
  • java 如何为文件及文件夹添加权限

    java 如何为文件及文件夹添加权限

    这篇文章主要介绍了java 如何为文件及文件夹添加权限的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • 使用eclipse + maven一步步搭建SSM框架教程详解

    使用eclipse + maven一步步搭建SSM框架教程详解

    SSM(Spring+SpringMVC+MyBatis)框架集由Spring、SpringMVC、MyBatis三个开源框架整合而成,常作为数据源较简单的web项目的框架.这篇文章主要介绍了eclipse + maven搭建SSM框架 ,需要的朋友可以参考下
    2017-11-11
  • AsyncHttpClient ChannelPool线程池频道池源码流程解析

    AsyncHttpClient ChannelPool线程池频道池源码流程解析

    这篇文章主要为大家介绍了AsyncHttpClient ChannelPool线程池频道池源码流程解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • idea2020.3配置maven环境并配置Tomcat的详细教程

    idea2020.3配置maven环境并配置Tomcat的详细教程

    这篇文章主要介绍了idea2020.3配置maven环境并配置Tomcat的详细教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • Spring Cloud Gateway组件的三种使用方式实例详解

    Spring Cloud Gateway组件的三种使用方式实例详解

    Spring Cloud Gateway是 Spring 官方基于 Spring5.0 、 SpringBoot2.0 和 Project Reactor 等技术开发的网关旨在为微服务框架提供一种简单而有效的统一的API 路由管理方式,统一访问接口,这篇文章主要介绍了Spring Cloud Gateway组件的三种使用方式,需要的朋友可以参考下
    2024-01-01
  • 关于使用POI向word中添加图片的问题

    关于使用POI向word中添加图片的问题

    这篇文章主要介绍了关于使用POI向word中添加图片的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • mybatis spring配置SqlSessionTemplate的使用方式

    mybatis spring配置SqlSessionTemplate的使用方式

    这篇文章主要介绍了mybatis spring配置SqlSessionTemplate的使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • 深入解读分布式事务Seata的XA模式

    深入解读分布式事务Seata的XA模式

    这篇文章主要介绍了深入解读分布式事务Seata的XA模式,XA 规范 描述了全局的事务管理器与局部的资源管理器之间的接口,XA规范 的目的是允许的多个资源在同一事务中访问,这样可以使 ACID 属性跨越应用程序而保持有效,需要的朋友可以参考下
    2023-08-08

最新评论