版本:java 17(版本无关紧要)
公共参数:application文件peizhi
oss:
endpoint:
accessKeyId:
accessKeySecret:
roleArn:
roleSessionName:
bucketName:
endpointoss:
domain:
bucketNamePath:
实体类:
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@Data
@ConfigurationProperties(prefix = "oss")
public class OSSProperty {
private String endpointoss;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
private String domain;
private String bucketNamePath;
}
工具类:
public String uploadFile(MultipartFile file, String pathPre) {
String bucketName = ossProperty.getBucketName();
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = ossProperty.getEndpointoss();
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = ossProperty.getAccessKeyId();
String accessKeySecret = ossProperty.getAccessKeySecret();
String domain = ossProperty.getDomain();
String bucketNamePath = ossProperty.getBucketNamePath();
String fileName = "";
fileName = fileNameRound(file.getOriginalFilename());
String url = "";
String path = PathUtils.generateFilePath(fileName);
if (StringUtils.isNotBlank(pathPre)) {
if (!"/".equals(pathPre.substring(0, 1))) {
pathPre = "/" + pathPre;
}
if (!"/".equals(pathPre.substring(pathPre.length() - 1, pathPre.length()))) {
pathPre = pathPre + "/";
}
path = pathPre + fileName;
}
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 获取文件名和扩展名
String originalFilename = file.getOriginalFilename();
path = bucketNamePath + path;
ossClient.putObject(bucketName, path, file.getInputStream());
url = domain + "/" + path; // url = "https://" + bucketName + "." + endpoint.substring(8) + "/" + path;
return url;
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return "";
}
private String fileNameRound(String fileName){
/**
* 文件上传会上传特殊文件,入blob格式的图片。在这里需要将后缀拼接上
*/
//原始文件名
if ("blob".equals(fileName)){
fileName = fileName + ".png";
}
// 这里是给文件命名,防止同个人同时上传同一个文件名的重复情况
//截取原始文件名的后缀 dfdfdf.png
String extension = fileName.substring(fileName.lastIndexOf("."));
//构造新文件名称
return com.ruoyi.common.utils.uuid.UUID.randomUUID().toString() + extension;
}
public static String generateFilePath(String fileName){
//根据日期生成路径 2024/1/1/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
String datePath = sdf.format(new Date());
//uuid作为文件名
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
return new StringBuilder().append(datePath).append(uuid).append("/").append(fileName).toString();
}
调用:
String filePathDate = "upload/" +currentDate.getYear() + "/" + currentDate.getMonthValue() + "/" + currentDate.getDayOfMonth();
//文件的请求路径
filePath = ossPathUtils.uploadFile(file, filePathDate);
// 1、第一个参数是前端上传到后端的文件
// 2、第二个参数是上传到OSS时上传到哪个文件夹
// 我在uploadFile放里面其实已经写了文件路径的修改了,这里我在OSS创建了一个upload文件夹,我希望我上传的文件夹都在upload文件夹里面。这里后面的时间也可以不用去拼接,只上传一个自己向指定的文件夹路径也行