目录
1、在pom.xml中添加如下依赖
2、在application.yml中添加如下配置
3、创建文件上传工具类
4、接口调用
1、在pom.xml中添加如下依赖
com.aliyun.oss
aliyun-sdk-oss
3.8.0
2、在application.yml中添加如下配置
oss: host: http://xxxx.oss-cn-shenzhen.aliyuncs.com bucketName: xxxx-uxm endpoint: oss-cn-shenzhen.aliyuncs.com accessKeyId: xxxx6rZ7etOfxxx accessKeySecret: xxxxxxxxxLc8NUoTTrmxxxxxxxxx
3、创建文件上传工具类
文件上传工具类:
@Data
@Component
@ConfigurationProperties(prefix = "uxm.oss")
public class OssUtil {
private String host;
private String bucketName;
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
public Object upload(MultipartFile file) {
if (file.isEmpty()) {
throw new ServiceException("上传文件不能为空");
}
if (!checkFileSize(file.getSize(), BaseConstant.LEN, BaseConstant.UNIT_M)) {
throw new ServiceException("上传文件大小不能超过10M");
}
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
// 保存路径,注意:这里不要以 / 或 开头
String path = new SimpleDateFormat("yyyyMMdd").format(new Date());
String originalFilename = file.getOriginalFilename();
String fileName = path + "/" + UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
try {
ossClient.putObject(bucketName, fileName, file.getInputStream());
} catch (IOException e) {
throw new ServiceException("上传失败" + e.getMessage());
}
// 关闭OSSClient。
ossClient.shutdown();
return host + "/" + fileName;
}
public void remove(String url) {
for (int i = 0; i < 3; i++) {
url = url.substring(url.indexOf("/") + 1);
}
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 删除操作
ossClient.deleteObject(bucketName, url);
// 关闭OSSClient。
ossClient.shutdown();
}
public boolean checkFileSize(Long len, int size, String unit) {
double fileSize = 0;
if (BaseConstant.UNIT_B.equals(unit.toUpperCase())) {
fileSize = (double) len;
} else if (BaseConstant.UNIT_K.equals(unit.toUpperCase())) {
fileSize = (double) len / 1024;
} else if (BaseConstant.UNIT_M.equals(unit.toUpperCase())) {
fileSize = (double) len / 1048576;
} else if (BaseConstant.UNIT_G.equals(unit.toUpperCase())) {
fileSize = (double) len / 1073741824;
}
if (fileSize > size) {
return false;
}
return true;
}
}
文件常量类:
public class BaseConstant {
public static final Integer NO = 0;
public static final Integer YES = 1;
public static final int LEN = 10;
public static final String UNIT_M = "M";
public static final String UNIT_B = "B";
public static final String UNIT_K = "K";
public static final String UNIT_G = "G";
}
4、接口调用
Controller:
@Valid
@RestController
@RequestMapping("/file")
@Api(tags = "上传文件", description = "上传文件API")
public class UploadFileController {
@Autowired
private OssUtil ossUtil;
@ApiOperation("文件/图片上传")
@PostMapping("/upload")
public Result



