ㅤㅤㅤ
ㅤㅤㅤ
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ(生活的道路一旦选定,就要勇敢地走到底,决不回头。——左拉)
ㅤㅤㅤ
ㅤㅤㅤ
ㅤㅤㅤㅤㅤㅤㅤㅤㅤ
版本信息
springboot:2.3.7
java: 1.8
用到的工具包
swagger-annotations:1.5.20
spring-web:5.2.11
soring-core:5.2.11
lombok:1.18.16
示例代码
package com.zhangzw.test.serverbase.interfaces.controller.file;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
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;
@Api(tags = "文件上传/下载API")
@RestController
@RequestMapping(value = "/file")
@Slf4j
public class FileController {
String fileBaseDir = "/nfs/test";
@ApiOperation("文件上传")
@PostMapping("/upload")
public JSONObject uploadFile(@RequestParam("file") MultipartFile file) {
if (file == null) {
// TODO 抛出异常 提示文件为空
}
String fullPath = fileBaseDir + "/";
File fullPathFolder = new File(fullPath);
StringBuilder fileUrl = new StringBuilder("/");
// 判断文件夹 不存在则创建
try {
if (!fullPathFolder.exists()) {
String[] splitList = fullPath.split("/");
// 递归创建文件夹
for (int i = 0; i < splitList.length; i++) {
String url = splitList[i];
if (StringUtils.isEmpty(url)) {
continue;
}
fileUrl.append(url).append("/");
File fileUrlUrl = new File(String.valueOf(fileUrl));
if (!fileUrlUrl.exists()) {
fileUrlUrl.mkdirs();
log.info("uploadFile 文件夹创建成功" + fileUrlUrl);
}
}
}
} catch (Exception e) {
log.error("uploadFile 文件夹创建失败" + e);
// TODO 抛异常 提示文件夹创建失败
}
// 处理文件扩展名
String originalname = file.getOriginalFilename();
if (StringUtils.isEmpty(originalname)) {
// TODO 抛出异常 提示文件名为空
}
String[] splitList = originalname.split("\\.");
String extensionName = splitList[splitList.length - 1];
String newFileName = "自定义文件名称" + "." + extensionName;
String newFileUrl = fullPath + "/" + newFileName;
try {
file.transferTo(new File(newFileUrl).getCanonicalFile());
} catch (Exception e) {
log.error("uploadFile 文件创建失败" + e);
// TODO 抛出异常 提醒文件创建失败
}
log.info("uploadFile 文件上传成功:" + newFileUrl);
// 使用fastjson
return new JSONObject()
.fluentPut("destination", fileUrl)
.fluentPut("fieldname", "file")
.fluentPut("filename", newFileName)
.fluentPut("mimetype", file.getContentType())
.fluentPut("originalname", originalname)
.fluentPut("path", newFileUrl)
.fluentPut("size", file.getSize());
}
}
示例请求
postman
curl
curl --location --request POST ‘http://localhost:3000/file/upload’
–form ‘=@“/D:/7moor/linshi/20220425/________.xlsx”’