FileUploadService.java
2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package cn.com.glsx.wechatbuild.service;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.InputStream;
/**
* @Title:
* @Description: 文件上传服务
* @Author xiehx
* @Date 2025/7/18
**/
@Slf4j
@Service
public class FileUploadService {
/**
* 上传文件流到阿里oss
*
* @param inputStream 文件流
* @param objectName 文件名
* @param endpointPost oss端点
* @param bucketName oss桶
* @param accessKeyId oss key
* @param accessKeySecret oss 秘钥
* @return
*/
public String uploadFileInputStreamToOss(InputStream inputStream,
String objectName,
String endpointPost,
String bucketName,
String accessKeyId,
String accessKeySecret) {
String fileUrl=null;
String endpoint = "https://"+ endpointPost;
if (org.apache.commons.lang3.StringUtils.isAnyBlank(endpointPost, bucketName, accessKeyId, accessKeySecret)) {
log.info("oss 配置存在缺失,请检查");
return "";
}
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
PutObjectResult result = ossClient.putObject(putObjectRequest);
log.info("Object upload successfully,object url is:{}", JSONObject.toJSONString(result));
fileUrl="https://" + bucketName + "." + endpointPost + "/" + objectName;
} catch (OSSException oe) {
log.info("Error Message:{}",oe.getErrorMessage());
log.info("Error Code:{}", oe.getErrorCode());
log.info("Request ID:{}",oe.getRequestId());
log.info("Host ID:{}",oe.getHostId());
} catch (ClientException ce) {
log.info("Error Message:{}",ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return fileUrl;
}
}