单文件与多文件上传

  1. 新建Spring项目:demo9,添加依赖:Spring Web、Spring Configuration Processor、Lombok和Thymeleaf。
  2. com.example.boot下新建控制器:controller.Demo9Controller。
package com.example.boot.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@Controller
public class Demo9Controller {
    @PostMapping("/upload")
    public String upload(@RequestPart("avatar") MultipartFile avatar,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {
        log.info("avatar.size={},photos.length={}",avatar.getSize(),photos.length);
        if(!avatar.isEmpty()){
            String originalFilename = avatar.getOriginalFilename();
            avatar.transferTo(new File("D:\\test\\"+originalFilename));
        }
        if(photos.length>0){
            for (MultipartFile photo : photos) {
                if(!photo.isEmpty()){
                    String originalFilename = photo.getOriginalFilename();
                    photo.transferTo(new File("D:\\test\\"+originalFilename));
                }
            }
        }
        return "main";
    }
}
  1. resources.templates下新建页面:index.html和main.html。
<!-- index.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <form th:action="@{/upload}" method="post" enctype="multipart/form-data">
        头像:<input type="file" name="avatar" /><br/>
        附件:<input type="file" multiple name="photos"/><br/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

<input type="file" />,上传单文件;<input type="file" multiple/>,上传多个文件。
注意哈,上传文件的表单,一定要加enctype="multipart/form-data",否则会遭遇如下报错:
org.springframework.web.multipart.MultipartException: Current request is not a multipart request

<!-- main.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>主页</title>
</head>
<body>
    <p>Main Page 欢迎您!</p>
</body>
</html>
  1. 启动应用并测试。
    在这里插入图片描述
  2. 重启应用,再测试一遍。
    在这里插入图片描述

上传多个文件时,报出异常:Maximum upload size exceeded;The field photos exceeds its maximum permitted size of 1048576 bytes.

进入MultipartAutoConfiguration,其定义如下:

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class })
@ConditionalOnProperty(prefix = "spring.servlet.multipart", name = "enabled", matchIfMissing = true)
@ConditionalOnWebApplication(type = Type.SERVLET)
@EnableConfigurationProperties(MultipartProperties.class)
public class MultipartAutoConfiguration {
	//...
}

自动配置类MultipartAutoConfiguration与类MultipartPropertie的属性进行了绑定,因此可在配置文件(如application.yml)中通过前缀spring.servlet.multipart+MultipartPropertie属性的方式进行自定义配置。

MultipartPropertie类的定义如下。

@ConfigurationProperties(prefix = "spring.servlet.multipart", ignoreUnknownFields = false)
public class MultipartProperties {

	/**
	 * Whether to enable support of multipart uploads.
	 */
	private boolean enabled = true;

	/**
	 * Intermediate location of uploaded files.
	 */
	private String location;

	/**
	 * Max file size.
	 */
	private DataSize maxFileSize = DataSize.ofMegabytes(1);

	/**
	 * Max request size.
	 */
	private DataSize maxRequestSize = DataSize.ofMegabytes(10);

	/**
	 * Threshold after which files are written to disk.
	 */
	private DataSize fileSizeThreshold = DataSize.ofBytes(0);
	//...
}

了解了这些之后,针对以上问题的解决方法是:扩大maxFileSize和maxRequestSize的值。
在application.yml中添加如下内容:

spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 100MB

重启应用并重新测试。
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值