springboot 上传批量上传图片
时间: 2023-02-06 19:05:49 浏览: 197
Spring Boot 上传图片的方法有多种,这里介绍一种使用 Apache Commons FileUpload 库的方法。
首先,在项目的 pom.xml 文件中添加依赖:
```
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
```
然后在你的 Spring Boot 应用程序中创建一个处理文件上传的控制器,示例代码如下:
```java
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
@Controller
public class FileUploadController {
@RequestMapping(value="/upload", method=RequestMethod.POST)
@ResponseBody
public String handleFileUpload(HttpServletRequest request) {
// 创建文件工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置缓存大小,如果文件大小超过缓存大小,将使用临时文件缓存
factory.setSizeThreshold(1024 * 1024 * 10); // 10 MB
// 设置临时文件目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 解析请求中的文件项
List<FileItem> fileItems = upload.parseRequest(request);
// 处理上传的文件项
for (FileItem item : fileItems) {
// 判断是否为文件项
if (!item.isFormField()) {
// 获取文件名
String fileName = item.getName();
// 获取文件的扩展名
String file
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)