SpringBoot单文件和多文件上传简单应用

本文详细介绍了如何在SpringBoot中实现单文件和多文件上传,包括配置、前端页面设计、后端处理逻辑及异常处理。适合初学者快速上手。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springBoot单文件上传和多文件上传

1. 开发工具版本介绍

springBoot版本:1.5
JDK版本:1.8
tomcat版本:7.0

2. pom配置
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

引入了spring-boot-starter-thymeleaf做页面模板引擎,写一些简单的上传示例

2. application.properties配置
#thymeleaf
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false


#上传文件
#默认支持文件上传.
spring.http.multipart.enabled=true 
#支持文件写入磁盘.
spring.http.multipart.file-size-threshold=0
#上传文件的临时目录 
spring.http.multipart.location=
# 最大支持文件大小
spring.http.multipart.max-file-size=1Mb
3.启动类配置
@SpringBootApplication
public class FileUploadWebApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(FileUploadWebApplication.class, args);
    }

    @Bean
    public TomcatServletWebServerFactory tomcatEmbedded() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
            if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
                //-1 means unlimited
                ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
            }
        });
        return tomcat;
    }

}

tomcatEmbedded解决上传文件大于10M出现连接重置的问题。此异常内容 GlobalException 也捕获不到。
springBoot1.5版本使用TomcatEmbeddedServletContainerFactory
springBoot2.0版本使用TomcatServletWebServerFactory

在这里插入图片描述

4.前端页面

上传页面:upload.html(就一个选择文件按钮和一个提交按钮)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>
</body>
</html>

上传结果页面:uploadStatus.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot - Upload Status</h1>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
</body>
</html>
5.业务处理类
/**
 * 跳转单文件上传页面
 * @return
 */
@GetMapping("/")
public String index() {
    return "upload";
}
	/**
	* 单文件上传
	 * @param file
	 * @param model
	 * @return
	 */
	@PostMapping("/uploadFile") 
	public String singleFileUpload(@RequestParam("file") MultipartFile file, Model model) {
	    if (file.isEmpty()) {
	    	model.addAttribute("message", "Please select a file to upload");
	        return "uploadStatus";
	    }
	    try {
	        byte[] bytes = file.getBytes();
	        Path path = Paths.get("D:/springUpload/" + file.getOriginalFilename());
	        Files.write(path, bytes);
	        model.addAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return "uploadStatus";
	}
6.异常类处理
package com.example.demo.controller.upload;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartException;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MultipartException.class)
    public String handleError1(MultipartException e, Model model) {
    	model.addAttribute("message", e.getCause().getMessage());
        return "uploadStatus";
    }
}

多文件处理

多文件上传更简单,只需要两个步骤,如下

  1. 前端上传控件添加multiple=“multiple”
    <input type="file" name="file" multiple="multiple" />
    
  2. 处理类接收使用数组MultipartFile[] files,循环每一个file就可以了
    @PostMapping("/uploadManyFile") 
    public String manyFileUpload(@RequestParam("file")  MultipartFile[] files, Model model) {
        if (files.length == 0) {
        	model.addAttribute("message", "Please select a file to upload");
            return "uploadStatus";
        }
        try {
        	Path path = null;
        	byte[] bytes = null;
        	for (MultipartFile file : files) {
        		bytes = file.getBytes();
    	        path = Paths.get("D:/springUpload/" + file.getOriginalFilename());
    	        Files.write(path, bytes);
    		}
        	model.addAttribute("message", "You successfully uploaded many file");
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return "uploadStatus";
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值