欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 文件上传

程序员文章站 2022-05-04 09:53:16
...

一、简介

java 中文件上传涉及CommonsMultipartResolver 和 StandardServletMultipartResolver,其中CommonsMultipartResolver需要 commons-fileupload jar 包。StandardServletMultipartResolver 基于Servlet3.0 将不再需要任何额外的jav 包,tomcat 7.0 开始支持Servlet3.0。spring boot 2.0.4 内嵌的tomcat 为8.5.32 。自动配置信息如下:

spring boot 文件上传
用户可自定义配置相关属性。

二、流程

1.FileController.java

package com.vincent;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController 
@RequestMapping("/file")
public class FileController {
	@PostMapping("/upload")
	public String upload(MultipartFile multipartFile) {
		
		String base = "C:\\Users\\Administrator\\Desktop\\file\\";
		File file = new File(base);
		if(!file.exists()) {
			file.mkdirs();
		}
		
		//获取文件类型名
		String[] parts = multipartFile.getOriginalFilename().split("\\.");
		String fileName = UUID.randomUUID().toString();
		
		if(parts!= null && parts.length >= 2) {
			fileName += "." + parts[parts.length-1];
		}
		try {
			multipartFile.transferTo(new File(base + fileName));
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			return "文件上传失败";
		}
		
		return fileName;
	}
	
	@GetMapping("/path")
	public void file(String fileName,HttpServletResponse response) throws IOException {
		
		String base = "C:\\Users\\Administrator\\Desktop\\file\\";
		
		byte[] bytes = Files.readAllBytes(Paths.get(base, fileName));
		response.getOutputStream().write(bytes);
		
	}
	
}

2.resources/static/html/index.html

<html>
	<head>
		<meta charset="utf-8" >
	</head>
	<body>
		<form action="/file/upload" method="post" enctype="multipart/form-data">
			<input type="file" name="multipartFile"><br/>
			<input type="submit" value="提交" /> 
		</form>
	</body>
</html>

三、测试

1.访问 http://localhost:8080/html/index.html

spring boot 文件上传

2.选择文件并提交

spring boot 文件上传

3.使用 FileController 中请求获取文件信息

spring boot 文件上传

四、多文件上传

1.html form 的input 支持multiple 属性,加上该属性将可以上传多个文件

2.多文件上传的请求方法的MultipartFile 将是一个数组,遍历该数组保存相关文件信息即可