这篇文章主要为大家详细介绍了springboot实现文件上传,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了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 将是一个数组,遍历该数组保存相关文件信息即可
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
本文标题为:spring boot实现文件上传
- Java实现顺序表的操作详解 2023-05-19
- 深入了解Spring的事务传播机制 2023-06-02
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- Java中的日期时间处理及格式化处理 2023-04-18
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- JSP页面间传值问题实例简析 2023-08-03
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- JSP 制作验证码的实例详解 2023-07-30