目录
虽然这个功能对应现在的分布式系统已不用了,但还是做个笔记吧,需要参考OSS云存储的见我 的这篇博客:
Springboot OSS 七牛云 上传、删除、访问图_Dragon Wu的博客-CSDN博客
一、添加配置
file:
# 本地域名/路径
root: localhost:8081
# 文件存储的相对路径
path: D:/dragonwu/test-file/ # Linux /dragonwu/test-file/
# 上传文件允许的扩展名
allowed: png,jpg,jpeg,pdf,bmp
二、上传的服务类
public interface LocalFileStorageService {
/**
* 上传文件到本地服务器
* @param file 文件
* @return 文件相对路径
*/
String upload(MultipartFile file) throws RuntimeException;
/**
* 删除单个文件
* @param filePath 删除文件路径名
* @return 成功true,失败false
*/
boolean delete(String filePath);
}
package com.dragonwu.service.impl;
import com.dragonwu.service.LocalFileStorageService;
import com.dragonwu.util.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;
/**
* @author Dragon Wu
* @since 2022-10-16 16:58
**/
@Service
public class LocalFileStorageServiceImpl implements LocalFileStorageService {
@Value("${file.root}")
private String root; //域名/路径
@Value("${file.path}")
private String path; // 存储路径
@Value("${file.allowed}")
private String[] allowed; //图片允许的扩展名
@Override
public String upload(MultipartFile file) throws RuntimeException {
//获取原始文件名
String originalFileName = Objects.requireNonNull(file.getOriginalFilename());
//判断文件是否允许上传
if (!isFileAllowed(originalFileName)) throw new IllegalArgumentException();
//生成文件名
String fileName = getRandomImgName(originalFileName);
//创建文件
File pathDir = new File(path + DateUtils.getTodayDate());
if (!pathDir.exists()) {
pathDir.mkdirs();
}
String key = path + DateUtils.getTodayDate() + "/" + fileName;
File dest = new File(key);
try {
file.transferTo(dest);
} catch (IOException e) {
throw new RuntimeException("上传失败");
}
return key;
}
@Override
public boolean delete(String filePath){
boolean flag = false;
//根据路径创建文件对象
File file = new File(filePath);
//路径是个文件且不为空时删除文件
if(file.isFile() && file.exists()){
flag = file.delete();
}
//删除失败时,返回false
return flag;
}
/**
* 生成唯一图片名称
*
* @param fileName 原文件名
* @return 云服务器fileName
*/
private static String getRandomImgName(String fileName) throws IllegalArgumentException {
int index = fileName.lastIndexOf(".");
if (fileName.isEmpty() || index == -1) {
throw new IllegalArgumentException();
}
// 获取文件后缀
String suffix = fileName.substring(index).toLowerCase();
// 生成UUID
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 拼接新的名称
return uuid + suffix;
}
/**
* 判断文件是否被允许上传
*
* @param fileName 文件名
* @return 允许true, 否则false
*/
private boolean isFileAllowed(String fileName) {
// 获取后缀名
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
for (String allow : allowed) {
if (allow.equals(suffixName)) {
return true;
}
}
return false;
}
}
三、控制层
package com.dragonwu.controller;
import com.dragonwu.service.LocalFileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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;
/**
* @author Dragon Wu
* @since 2022-10-15 17:09
**/
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
private LocalFileStorageService localFileStorageService;
@PostMapping("/upload")
public String upload(@RequestParam MultipartFile file) {
//上传文件到七牛云服务器
//把图片放到距离图片最近的服务器上,降低我们自身服务器的带宽消耗
try {
return localFileStorageService.upload(file);
} catch (RuntimeException e) {
return e.getMessage();
}
}
@DeleteMapping("/delete")
public String delete(@RequestParam String key) {
try {
return localFileStorageService.delete(key)?"文件已删除":"删除失败";
} catch (RuntimeException e) {
return e.getMessage();
}
}
}
四、测试
上传到对应路径:
文件删除:
文件删除成功!