Spring boot 多文件上传注意要点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/magi1201/article/details/82757063

springboot多文件上传时,应注意以下要点:

1、多文件采用MultipartFile[ ]接收

2、单个文件信息对MultipartFile对象进行解析

3、上传文件大小spring.http.multipart.max-file-size设置

4、测试中上传目标目录的设置

下面我们通过一个示例来进行演示,其文件目录如下

主要文件有上传控制类FileUploadController.java和上传页面uploads.html,附加springboot默认配置文件application.properties。success.html 和 error.html是上传成功或失败的跳转页面,这里不展示其代码。

上传页面uploads.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>多文件上传示例</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}"/> 
<script type="text/javascript" th:src="@{js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
</head>
<body>
<div class="panel panel-primary">
	<div class="panel-heading">
		<h3 class="panel-title">文件上传示例:多文件上传</h3>
	</div>
</div>
<div class="container">
	<div class="row">
		<div class="col-md-8">
			<form class="form-horizontal" action="uploads" enctype="multipart/form-data" method="post">
				<div class="form-group">
					<div class="input-group col-md-4">
						<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
						<input class="form-control" placeholder="文件描述" type="text" name="descriptions" />
						<input class="form-control" placeholder="文件描述" type="text" name="descriptions" />
					</div>
				</div>
				<div class="form-group">
					<div class="input-group col-md-4">
						<span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span>
						<input class="form-control" placeholder="请选择文件" type="file" name="files"/>
						<input class="form-control" placeholder="请选择文件" type="file" name="files"/>
					</div>
				</div>
				<div class="form-group">
					<div class="col-md-4">
						<div class="btn-group btn-group-justified" >
							  <div class="btn-group" >
							    <button type="submit" class="btn btn-success" id="submitbtn">
							    	<span class="glyphicon glyphicon-share"></span>&nbsp;文件上传</button>
							  </div>
						</div>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>
</body>
</html>

相较于单文件上传,上面表单中有两个name标签属性,分别是descriptions和files,分别接收上传的文件描述和文件。如果把上面的多个描述框和上传控件都改为一个,则为单文件上传。

上传控制类FileUploadController.java

package com.example.fileupload.controller;

import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 多文件上传控制类
 * @author Administrator
 */
@Controller
public class FilesUploadController {
	
	// 读取application.properties文件中的自定义配置项
	@Value("${spring.fileupload.destination}")
	private String destination;
	
	@RequestMapping("/files")
	public String index(){
		return "uploads";
	}
	
	/**
	 * 多文件上传类
	 * 文件会自动绑定到MultipartFile中
	 * @param request 获取请求信息
	 * @param description 文件描述
	 * @param file 上传的文件
	 * @return 上传成功或失败结果
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@PostMapping("/uploads")
	public String filesUpload(HttpServletRequest request, 
			@RequestParam("descriptions") String[] descriptions,
			@RequestParam("files") MultipartFile[] files) throws IllegalStateException, IOException {
		
		// 获取文件描述参数 description,纯粹测试使用
		if (null != descriptions && descriptions.length > 0) {
			for (int i=0; i < descriptions.length; i++) {
				String description = descriptions[i];
				System.out.println("description" + i + " = " + description);
			}
		}
		
		// 构建上传文件的存放路径
		String destionation = destination + File.separator + "upload";
		System.out.println("destionation = " + destionation);
					
		// 如果文件不为空,写入上传路径,进行文件上传
		if (null != files && files.length > 0) {
			for (MultipartFile file : files) {
				// 测试MultipartFile接口的各个方法
				System.out.println("文件类型ContentType=" + file.getContentType());
				System.out.println("文件组件名称Name=" + file.getName());
				System.out.println("文件原名称OriginalFileName=" + file.getOriginalFilename());
				System.out.println("文件大小Size=" + file.getSize() + "byte or " + file.getSize()/1024 + "KB");
				saveFile(file, destionation);
			}
			return "success";
		} else {
			return "error";
		}
	}
	
	/**
	 * 文件保存方法
	 * @param file
	 * @param destination
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	private void saveFile(MultipartFile file, String destination) throws IllegalStateException, IOException {
		// 获取上传的文件名称,并结合存放路径,构建新的文件名称
		String filename = file.getOriginalFilename();
		File filepath = new File(destination, filename);
		
		// 判断路径是否存在,不存在则新创建一个
		if (!filepath.getParentFile().exists()) {
			filepath.getParentFile().mkdirs();
		}
		
		// 将上传文件保存到目标文件目录
		file.transferTo(new File(destination + File.separator + filename));
	}
}

解读点1、自定义配置项读取

// 读取application.properties文件中的自定义配置项

@Value("${spring.fileupload.destination}")
private String destination;

我们在application.properties文件中新增加spring.fileupload.destination=D:\\DEV_ENV配置项,该配置项可以通过@Value注解自动注入给@Value注解标注的属性。这里注意不同操作系统间的分隔符,我们这里是Windows系统,使用双反斜线 "\\"。

解读点2、页面文件信息映射

@RequestParam("descriptions") String[] descriptions, @RequestParam("files") MultipartFile[] files

方法入参中descriptions 和 files 接收反射过来的页面的descriptions 和 files ,其实突然想到,页面的description和file标签位置可以调整下,调整到一行,就俨然一个上传功能的雏形了。

解读点3、MultipartFile方法测试

file.getContentType() 获取文件类型信息,如image/jpg、application/pdf等

file.getName() 获取表单上传组件的name值,我们上面的<input type="file"  ... name="files"/> 该值变为files了

file.getOriginalFilename() 获取原上传文件名称,有利于文件的保存、查找等

file.getSize() 获取文件大小,默认单位是字节(byte),可以根据需要转换为千字节(KB)或兆(MB)

application.properties文件

spring.http.multipart.max-file-size=45MB
spring.http.multipart.max-request-size=50MB
spring.fileupload.destination=D:\\DEV_ENV

spring.http.multipart.max-file-size 单个文件的最大大小控制

spring.http.multipart.max-request-size 单次请求的所有文件的最大大小控制,主要用在多文件上传时

下面进入测试

场景1、双文件正常上传

测试时,我们首先一个44.5MB的PDF文件和一个385byte的TXT文件,文件可以正常上传

查看后台的打印信息

description0 = jpa建表注释
description1 = Tomcat权威指南
destionation = D:\DEV_ENV\upload
文件类型ContentType=text/plain
文件组件名称Name=files
文件原名称OriginalFileName=jpa建表注释.txt
文件大小Size=385byte or 0KB
文件类型ContentType=application/pdf
文件组件名称Name=files
文件原名称OriginalFileName=TOMCAT权威指南.pdf
文件大小Size=46711873byte or 45617KB
与我们期待的结果一致,PDF文件和TXT文件均上传成功,到指定的目录,可以正常打开查看

场景2、双文件总大小超大,上传失败

后台会报错,主要信息如下 

org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (52507104) exceeds the configured maximum (52428800)] with root cause

请求被拒,因为请求文件大小52507104byte超过了允许的最大文件大小52428800byte(即50MB)。

以上是最近学习整理的关于多文件上传的内容,用文章予以记录,希望可以帮助到大家,同时对文章中可以改进的部分,欢迎大家留言批评斧正。谢谢。

附带源码下载:springboot单文件和多文件上传

猜你喜欢

转载自blog.csdn.net/magi1201/article/details/82757063
今日推荐