SpringBoot-图片上传
1. 准备
1.1 springboot上传文件大小配置
servlet:
multipart:
max-file-size: 128MB #上传文件总大值
max-request-size: 10MB #单个文件的最大值
1.2 在配置文件重配置上传地址
在进行文件上传时会存在上传到多个位置,可以通过如下配置进行区分,有效统一地址操作,避免不必要的误操作。
#文件上传操作
uploadFile:
resourceHandler: /upload_img/ #请求 url 中的资源映射也是保存到数据库中的父级路径
staticAccessPath: /upload_img/**
location: /root/uploadFiles/
1.3 创建保存图片地址信息对象
由于可能会对图片进行上传后马上保存到后端数据库,于是建立了一个视图对象信息方式返回前端。
@Data
public class ToolesImagesVO {
private Integer id; // 自增id
private String filePath; // 图片地址
}
2.图片上传
2.1 文件上传控制方法
@RestController
@RequestMapping("/files/")
@Api(value = "files", tags = "文件操作")
public class ToolesFilesUploadController {
// 引用配置地址
@Value("${uploadFile.resourceHandler}")
private String resourceHandler;
@Value("${uploadFile.location}")
private String location;
@Value("${uploadFile.productImagesPath}")
private String productImagesPath;
@ApiOperation(value = "图片上传", notes = "图片上传")
@PostMapping(value = "/product/imageUpload", headers = "content-type=multipart/form-data")
@ResponseBody
public Object productImageUpload(@RequestParam(value = "images") MultipartFile images, HttpServletRequest request) throws Exception {
if (StringUtils.isEmpty(images)) {
return ResponseUtil.fail(BADARGUMENTVALUE, "上传图片为空!");
}
String fileName = images.getOriginalFilename(); // 文件名称
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 图片后缀
ToolesImagesVO vo = new ToolesImagesVO();
// 判断文件后缀是否为后端默认的后缀名
if (isImageFile(suffixName)) {
fileName = UUID.randomUUID() + suffixName; // 新图片名称
String saveToPath = resourceHandler + productImagesPath + DateUtils.getDate() + "/"; // 域名访问的相对路径(通过浏览器访问的链接-虚拟路径)
String realPath = location + productImagesPath + DateUtils.getDate() + "/"; // 真实路径,实际储存的路径
String filepath = realPath + fileName; // 储存文件的物理路径,使用本地路径储存
FileUtils.uploadFile(images, filepath, realPath, fileName); // 文件保存
String basePath = HttpUtils.getBasePath(request);
vo.setFilePath(basePath + saveToPath + fileName);
}
return ResponseUtil.ok(vo);
}
// 判断后缀
private Boolean isImageFile(String fileName) {
String[] img_type = new String[]{".jpg", ".jpeg", ".png", ".bmp"};
if (fileName == null) {
return false;
}
fileName = fileName.toLowerCase();
for (String type : img_type) {
if (fileName.endsWith(type)) {
return true;
}
}
return false;
}
}
2.2 文件上传实现
public class FileUtils extends org.apache.commons.io.FileUtils{
/**
* 功能描述:文件上传
*
* @param: [file, filepath, realPath, fileName]
* @author: Eggsy
* @date: 2021-01-22 17:47:42
* @return: boolean
**/
public static boolean uploadFile(MultipartFile file, String filepath, String realPath, String fileName){
boolean flag = false;
File dest = new File(filepath); // 判断有没有对应的文件夹
if (!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
try {
uploadFile(file.getBytes(),realPath,fileName);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
private static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
System.out.println("创建文件夹");
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
}