spring boot 文件上传

一、简介

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

在这里插入图片描述
用户可自定义配置相关属性。

二、流程

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

在这里插入图片描述

2.选择文件并提交

在这里插入图片描述

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

在这里插入图片描述

四、多文件上传

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

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

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值