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

发布时间 - 2026-01-11 00:17:58    点击率:

使用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

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


# spring  # boot  # 文件上传  # springboot多文件上传  # springboot上传的文件  # springboot实现单文件和多文件上传  # SpringBoot实现文件上传接口  # springboot上传图片文件步骤详解  # SpringBoot实现文件上传功能  # SpringBoot简单实现文件上传  # SpringBoot文件上传(本地存储)回显前端操作方法  # 上传  # 可选  # 最简单  # 创建一个  # 抛出  # 大家多多  # 新建一个  # 主要是  # 本例  # 使用了  # 源代码下载  # annotation  # bind  # stereotype  # RequestParam  # RequestMethod  # ResponseBody  # RequestMapping  # HttpServletRequest 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Laravel如何记录日志_Laravel Logging系统配置与自定义日志通道  如何用PHP工具快速搭建高效网站?  奇安信“盘古石”团队突破 iOS 26.1 提权  如何用wdcp快速搭建高效网站?  Laravel如何优化应用性能?(缓存和优化命令)  Laravel API路由如何设计_Laravel构建RESTful API的路由最佳实践  Laravel如何实现多表关联模型定义_Laravel多对多关系及中间表数据存取【方法】  Python自动化办公教程_ExcelWordPDF批量处理案例  Laravel怎么上传文件_Laravel图片上传及存储配置  香港服务器网站生成指南:免费资源整合与高速稳定配置方案  Laravel如何使用Socialite实现第三方登录?(微信/GitHub示例)  html5audio标签播放结束怎么触发事件_onended回调方法【教程】  rsync同步时出现rsync: failed to set times on “xxxx”: Operation not permitted  西安市网站制作公司,哪个相亲网站比较好?西安比较好的相亲网站?  JS实现鼠标移上去显示图片或微信二维码  Laravel如何创建自定义Facades?(详细步骤)  手机网站制作与建设方案,手机网站如何建设?  如何快速辨别茅台真假?关键步骤解析  如何用已有域名快速搭建网站?  宙斯浏览器文件分类查看教程 快速筛选视频文档与图片方法  弹幕视频网站制作教程下载,弹幕视频网站是什么意思?  如何快速上传自定义模板至建站之星?  Laravel如何实现用户密码重置功能?(完整流程代码)  北京专业网站制作设计师招聘,北京白云观官方网站?  laravel怎么配置Redis作为缓存驱动_laravel Redis缓存配置教程  小视频制作网站有哪些,有什么看国内小视频的网站,求推荐?  Laravel怎么解决跨域问题_Laravel配置CORS跨域访问  Linux虚拟化技术教程_KVMQEMU虚拟机安装与调优  如何在万网自助建站中设置域名及备案?  桂林网站制作公司有哪些,桂林马拉松怎么报名?  Laravel事件监听器怎么写_Laravel Event和Listener使用教程  网站页面设计需要考虑到这些问题  Linux安全能力提升路径_长期防护思维说明【指导】  iOS正则表达式验证手机号、邮箱、身份证号等  Laravel怎么进行浏览器测试_Laravel Dusk自动化浏览器测试入门  Laravel任务队列怎么用_Laravel Queues异步处理任务提升应用性能  Laravel怎么连接多个数据库_Laravel多数据库连接配置  node.js报错:Cannot find module &#39;ejs&#39;的解决办法  如何在香港免费服务器上快速搭建网站?  如何在腾讯云服务器快速搭建个人网站?  php结合redis实现高并发下的抢购、秒杀功能的实例  ,交易猫的商品怎么发布到网站上去?  Win11摄像头无法使用怎么办_Win11相机隐私权限开启教程【详解】  海南网站制作公司有哪些,海口网是哪家的?  详解免费开源的.NET多类型文件解压缩组件SharpZipLib(.NET组件介绍之七)  HTML5建模怎么导出为FBX格式_FBX格式兼容性及导出步骤【指南】  高防服务器租用如何选择配置与防御等级?  Win11关机界面怎么改_Win11自定义关机画面设置【工具】  如何快速选择适合个人网站的云服务器配置?  php中::能调用final静态方法吗_final修饰静态方法调用规则【解答】