SpringBoot 实现文件上传下载
程序员文章站
2022-05-01 08:05:20
...
1. 创建boot工程,添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
2. 配置文件
server.port=8091
server.servlet.context-path=/
# 上传文件总的最大值
spring.servlet.multipart.max-request-size=10MB
# 单个文件的最大值
spring.servlet.multipart.max-file-size=10MB
3. 单文件上传案例
package com.javaboy.file.controller;
import lombok.extern.slf4j.Slf4j;
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.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* @author: gaoyang
* @date: 2021-03-23 09:28
* @description: 文件上传下载
*/
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
@PostMapping("/upload")
public String upload(@RequestParam(name = "file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
// 获取文件名
String filename = file.getOriginalFilename();
// 获取文件后缀
String suffix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
// 如果目录不存在则创建
File fullDir = new File("D:/file/test/");
if (!fullDir.exists()) {
fullDir.mkdirs();
}
// 保存文件
String path = filename + "." + suffix;
String fullPath = fullDir + path;
File dest = new File(fullPath);
try {
file.transferTo(dest);
log.info("上传成功");
return "上传成功";
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
}
return "上传失败";
}
}