Java将文件上传到云服务器

前言

今天总结了一个云上传的小demo特地来跟大家分享下。

这个demo可以将一些文件上传到云服务器。我们来看下吧。

正文

我这里使用了阿里云、亚马逊S3和微软Azure这三种云上传做的demo。

要使用云上传,我们需要引入相关jar包,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!--阿里云OSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.2.3</version>
</dependency>
<!--微软Azure-->
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-storage</artifactId>
<version>7.0.0</version>
</dependency>
<!--亚马逊S3-->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.8.9.1</version>
</dependency>
<!-- 腾讯云cos -->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.5.3</version>
</dependency>

PS:如果只使用一种云上传方式,引入对应的jar包即可,不必全部引入。

我们可以提供一个通用的上传接口upload,而具体的上传逻辑让各个实现类去实现。

同时我们暴露公共方法出来供上传使用。

上传的文件有可能是本地文件,也有可能是前端传过来的Base64图片字符串,也有可能是MultipartFile等。

我们提供一个抽象的上传方法,大致如下:

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
public abstract class UploadAbstractUtil {

public static final Logger logger = LoggerFactory.getLogger(UploadAbstractUtil.class);

/**
* 文件缓存路径
*/
private String basedir;

public UploadAbstractUtil(String basedir) {
this.basedir = basedir;
}

/**
* 上传文件到云
* @param tempFile
* @param realName
* @return
*/
protected abstract String upload(File tempFile, String realName);

/**
* 上传文件到云
* @param file
* @return
*/
abstract String upload(MultipartFile file);

/**
* 上传文件到云
* @param bytes
* @param contentType
* @return
*/
protected abstract String upload(byte[] bytes,String contentType);

/**
* 尝试初始化客户端
*/
protected abstract void initClient();

/**
* 生成一个唯一的上传文件名
* @param file
* @return
*/
protected String generateUploadFileName(MultipartFile file){
String name = file.getOriginalFilename();
String ext = name.substring(name.lastIndexOf("."));
String uuid = UUID.randomUUID().toString();
// 生成唯一的key
return uuid + ext;
}

/**
* base64转为文件后在进行上传
* @param base64Str
* @return
*/
public String base64UploadUseTempFile(String base64Str){
String realName = UUID.randomUUID().toString() + ".jpg";
File file = new File(basedir + "/" + realName);

if (!file.exists()) {
try {
file.createNewFile();
}catch (IOException e){
logger.error("文件上传,尝试创建文件时失败!!!",e);
throw new RuntimeException("文件上传失败!!!");
}
}

boolean flag = Base64Utils.Base64ToImage(base64Str, file.getPath());
if(!flag){
throw new RuntimeException("base64转换为文件时发生错误!!!");
}
String url;
try {
long startTime = System.currentTimeMillis();
url = upload(file, realName);
logger.info("tempFile---上传服务耗时------time:[{}ms]", System.currentTimeMillis()-startTime);
} catch (Exception e) {
logger.error("文件上传,上传文件时发生异常!!!",e);
throw new RuntimeException("文件上传失败!");
}
if (file.exists()) {
file.delete();
}
return url;
}

/**
* 通用文件上传
* @param filePath 文件路径
* @return
*/
public String fileUpload(String filePath){
if(StringUtils.isBlank(filePath)){
throw new RuntimeException("请输入正确的文件路径!");
}
File file = new File(filePath);
if(!file.exists()){
throw new RuntimeException("请输入正确的文件路径!");
}
int position = filePath.lastIndexOf(".");
String fileSuffix = "";
if(position > 0){
fileSuffix = filePath.substring(position);
}
//上传到云上的文件名
String realName = UUID.randomUUID().toString() + fileSuffix;
String url;
try {
long startTime = System.currentTimeMillis();
url = upload(file, realName);
logger.info("filePath---上传服务耗时------time:[{}ms]", System.currentTimeMillis()-startTime);
} catch (Exception e) {
logger.error("文件上传,上传文件时发生异常!!!",e);
throw new RuntimeException("文件上传失败!");
}
return url;
}


/**
* 使用流来进行文件上传
* @param base64Str
* @return
*/
public String base64UploadUseInputStream(String base64Str){
byte[] bytes = Base64Utils.Base64ToByte(base64Str);
String url;
try {
long startTime = System.currentTimeMillis();
url = upload(bytes,"image/jpeg");
logger.info("Stream---上传服务耗时------time:[{}ms]", System.currentTimeMillis()-startTime);
} catch (Exception e) {
logger.error("文件上传,上传文件时发生异常!!!",e);
throw new RuntimeException("文件上传失败!");
}
return url;
}

}

PS: 这个类看着比较多……其实都是对文件进行处理,生成上传文件名,然后交给上传方法,开始写的时候代码较少,在学习优化的过程中不断添加新功能,导致了该结果。

上面的上传抽象类大致逻辑如下:

针对图片文件:

  • 如果在服务器上的,可以直接获取到文件后进行上传。(fileUpload方法)
  • 如果APP端传过来的Base64编码的图片文件,可以把它生成临时文件,然后进行上传,也可以直接把Base64转换为流后进行上传。(base64UploadUseTempFile方法和base64UploadUseInputStream方法)
  • 如果APP端传过来MultipartFile文件,直接将其进行转换并上传。(upload(MultipartFile file)方法)

对于每种云上传,各个实现类具体如下:

阿里云OSS

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
public class AliOssUploadUtil extends UploadAbstractUtil{

public static final Logger logger = LoggerFactory.getLogger(AliOssUploadUtil.class);
/**
* 阿里云accessKey
*/
private String aliyunaccessKey;
/**
* 阿里云secretKey
*/
private String aliyunsecretKey;
/**
* 阿里云endpoint
*/
private String aliyunendpoint;
/**
* 阿里云endpointexternal
*/
private String aliyunendpointexternal;
/**
* 阿里云bucket
*/
private String aliyunbucket;

/**
* ossClient
*/
private OSSClient ossClient;

/**
* 构造器
* @param basedir
* @param aliyunaccessKey
* @param aliyunsecretKey
* @param aliyunendpoint
* @param aliyunendpointexternal
* @param aliyunbucket
*/
public AliOssUploadUtil(String basedir, String aliyunaccessKey, String aliyunsecretKey, String aliyunendpoint, String aliyunendpointexternal, String aliyunbucket) {
super(basedir);
this.aliyunaccessKey = aliyunaccessKey;
this.aliyunsecretKey = aliyunsecretKey;
this.aliyunendpoint = aliyunendpoint;
this.aliyunendpointexternal = aliyunendpointexternal;
this.aliyunbucket = aliyunbucket;
}

/**
* 阿里云文件上传
* @param tempFile
* @param realName
* @return
*/
@Override
protected String upload(File tempFile,String realName){
initClient();
ossClient.putObject(aliyunbucket, realName, tempFile);
URL url = ossClient.generatePresignedUrl(aliyunbucket, realName, new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100));
String urlString = String.valueOf(url).split("\\?")[0];
logger.info("阿里云OSS上传服务------图片内网url:[{}]", urlString);
urlString = urlString.replaceAll(aliyunendpoint, aliyunendpointexternal);
logger.info("阿里云OSS上传服务------图片外网url:[{}]", urlString);
return urlString;
}

/**
* 阿里云文件上传
* @param file
* @return
*/
@Override
String upload(MultipartFile file) {
initClient();
String key = generateUploadFileName(file);
try (InputStream is = new ByteArrayInputStream(file.getBytes())) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentEncoding(StandardCharsets.UTF_8.name());
metadata.setContentLength(file.getSize());
metadata.setContentType(file.getContentType());
// 上传
ossClient.putObject(aliyunbucket,key, is, metadata);
URL url = ossClient.generatePresignedUrl(aliyunbucket, key, new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100));
String urlString = String.valueOf(url).split("\\?")[0];
logger.info("阿里云OSS上传服务------图片内网url:[{}]", urlString);
urlString = urlString.replaceAll(aliyunendpoint, aliyunendpointexternal);
logger.info("阿里云OSS上传服务------图片外网url:[{}]", urlString);
return urlString;
}catch (IOException e){
logger.error("使用阿里云OSS上传文件出现异常",e);
throw new RuntimeException(e);
}
}

/**
* 尝试初始化client
*/
@Override
protected void initClient() {
if(ossClient == null){
ossClient = new OSSClient(aliyunendpoint, aliyunaccessKey, aliyunsecretKey);
}
}

@Override
protected String upload(byte[] bytes, String contentType) {
initClient();
String realName = UUID.randomUUID().toString() + ".jpg";
try (InputStream is = new ByteArrayInputStream(bytes)) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentEncoding(StandardCharsets.UTF_8.name());
metadata.setContentLength(is.available());
metadata.setContentType(contentType);
// 上传
ossClient.putObject(aliyunbucket,realName, is, metadata);
URL url = ossClient.generatePresignedUrl(aliyunbucket, realName, new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100));
String urlString = String.valueOf(url).split("\\?")[0];
logger.info("阿里云OSS上传服务------图片内网url:[{}]", urlString);
urlString = urlString.replaceAll(aliyunendpoint, aliyunendpointexternal);
logger.info("阿里云OSS上传服务------图片外网url:[{}]", urlString);
return urlString;
}catch (IOException e){
logger.error("使用阿里云OSS上传文件出现异常",e);
throw new RuntimeException(e);
}
}

/**
* shutdown Client
*/
public void shutdown(){
ossClient.shutdown();
}
}

亚马逊S3

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
public class AmazonS3UploadUtil extends UploadAbstractUtil{
/**
* S3 accessKey
*/
private String s3accessKey;
/**
* S3 secretKey
*/
private String s3secretKey;
/**
* S3 endpoint
*/
private String s3endpoint;
/**
* S3 bucket
*/
private String s3bucket;

/**
* 协议
*/
private static Protocol protocol = Protocol.HTTP;

/**
* 亚马逊s3 client
*/
private AmazonS3 client;

/**
* 构造器
* @param basedir
* @param s3accessKey
* @param s3secretKey
* @param s3endpoint
* @param s3bucket
*/
public AmazonS3UploadUtil(String basedir, String s3accessKey, String s3secretKey, String s3endpoint, String s3bucket) {
super(basedir);
this.s3accessKey = s3accessKey;
this.s3secretKey = s3secretKey;
this.s3endpoint = s3endpoint;
this.s3bucket = s3bucket;
}

/**
* 上传文件到 Amazon S3
* @param tempFile
* @param realName
* @return
*/
@Override
protected String upload(File tempFile, String realName){
try {
initClient();
client.setEndpoint(s3endpoint);
client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
client.putObject(new PutObjectRequest(s3bucket, realName, tempFile)
.withCannedAcl(CannedAccessControlList.AuthenticatedRead));
String imageUrl = "http://" + s3endpoint + "/" + s3bucket + "/" + realName;
logger.info("亚马逊S3上传服务------图片url:[{}]", imageUrl);
return imageUrl;
} catch (AmazonClientException e) {
logger.error("使用亚马逊S3上传文件出现异常",e);
throw new RuntimeException(e);
}
}

/**
* 上传文件到S3
* @param file
* @return
*/
@Override
String upload(MultipartFile file) {
initClient();
String key = generateUploadFileName(file);
try (InputStream is = new ByteArrayInputStream(file.getBytes())){
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentEncoding(StandardCharsets.UTF_8.name());
metadata.setContentLength(file.getSize());
metadata.setContentType(file.getContentType());
PutObjectRequest mall = new PutObjectRequest(s3bucket, key, is, metadata)
.withCannedAcl(CannedAccessControlList.AuthenticatedRead);
// 上传
client.putObject(mall);
return "http://" + s3endpoint + "/" + s3bucket + "/" + key;
}catch (IOException e){
logger.error("使用亚马逊S3上传文件出现异常",e);
throw new RuntimeException(e);
}
}

/**
* 尝试初始化S3Client
*/
@Override
protected void initClient() {
if(client == null){
AWSCredentials credential = new BasicAWSCredentials(s3accessKey, s3secretKey);
ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setProtocol(protocol);
client = new AmazonS3Client(credential, clientConfig);
}
}

@Override
protected String upload(byte[] bytes, String contentType) {
initClient();
String realName = UUID.randomUUID().toString() + ".jpg";
try (InputStream is = new ByteArrayInputStream(bytes)){
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentEncoding(StandardCharsets.UTF_8.name());
metadata.setContentLength(is.available());
metadata.setContentType(contentType);
PutObjectRequest mall = new PutObjectRequest(s3bucket, realName, is, metadata)
.withCannedAcl(CannedAccessControlList.AuthenticatedRead);
// 上传
client.putObject(mall);
return "http://" + s3endpoint + "/" + s3bucket + "/" + realName;
}catch (IOException e){
logger.error("使用亚马逊S3上传文件出现异常",e);
throw new RuntimeException(e);
}
}
}

微软Azure

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
public class AzureUploadUtil extends UploadAbstractUtil{
/**
* 用户名
*/
private String accountName;
/**
* 密码
*/
private String accountKey;
/**
* endPoint
*/
private String endPoint;
/**
* containerName
*/
private String containerName;
/**
* 连接串
*/
private String storageConnectionString;

/**
* Azure client
*/
private CloudBlobClient blobClient;

/**
* 构造器
* @param accountName
* @param accountKey
* @param endPoint
* @param containerName
*/
public AzureUploadUtil(String basedir,String accountName, String accountKey, String endPoint, String containerName) {
super(basedir);
this.accountName = accountName;
this.accountKey = accountKey;
this.endPoint = endPoint;
this.containerName = containerName;
this.storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="+ accountName +";AccountKey="+ accountKey +";EndpointSuffix=" + endPoint;
}

/**
* 上传文件到Azure
* @param
* @return
*/
@Override
protected String upload(File tempFile,String realName) {
try {
initClient();
CloudBlobContainer container = blobClient.getContainerReference(containerName);
// Create the container if it does not exist with public access.
container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());
//Getting a blob reference
CloudBlockBlob blob = container.getBlockBlobReference(tempFile.getName());
//Creating blob and uploading file to it
blob.uploadFromFile(tempFile.getAbsolutePath());
String imageUrl = "https://"+ accountName +".blob."+ endPoint +"/"+ containerName +"/" + tempFile.getName();
logger.info("微软Azure上传服务------图片url:[{}]", imageUrl);
return imageUrl;
} catch (IOException| StorageException | URISyntaxException e) {
logger.error("使用微软Azure上传文件出现异常",e);
throw new RuntimeException(e);
}
}

/**
* 上传文件到Azure
* @param file
* @return
*/
@Override
String upload(MultipartFile file) {
initClient();
String key = generateUploadFileName(file);
try(InputStream is = new ByteArrayInputStream(file.getBytes())){
CloudBlobContainer container = blobClient.getContainerReference(containerName);
// Create the container if it does not exist with public access.
container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());
CloudBlockBlob blob = container.getBlockBlobReference(key);
//Creating blob and uploading file to it
blob.upload(is, is.available());
return "https://"+ accountName +".blob."+ endPoint +"/"+ containerName +"/" + key;
}catch (IOException| StorageException | URISyntaxException e){
logger.error("使用微软Azure上传文件出现异常",e);
throw new RuntimeException(e);
}
}

/**
* 尝试初始化client
*/
@Override
protected void initClient(){
if(blobClient == null){
try{
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
blobClient = storageAccount.createCloudBlobClient();
}catch (URISyntaxException|InvalidKeyException e){
logger.error("使用微软Azure初始化client失败!",e);
throw new RuntimeException(e);
}
}
}

@Override
protected String upload(byte[] bytes, String contentType) {
initClient();
String realName = UUID.randomUUID().toString() + ".jpg";
try(InputStream is = new ByteArrayInputStream(bytes)){
CloudBlobContainer container = blobClient.getContainerReference(containerName);
// Create the container if it does not exist with public access.
container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());
CloudBlockBlob blob = container.getBlockBlobReference(realName);
//Creating blob and uploading file to it
blob.upload(is, is.available());
return "https://"+ accountName +".blob."+ endPoint +"/"+ containerName +"/" + realName;
}catch (IOException| StorageException | URISyntaxException e){
logger.error("使用微软Azure上传文件出现异常",e);
throw new RuntimeException(e);
}
}
}

腾讯云COS

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
public class TencentCOSUploadUtil extends UploadAbstractUtil {

public static final Logger logger = LoggerFactory.getLogger(TencentCOSUploadUtil.class);
/**
* 腾讯云COS AccessKey
*/
private String qAccessKey;
/**
* 腾讯云COS SecretKey
*/
private String qSecretKey;
/**
* 腾讯云COS bucket
*/
private String qBucket;
/**
* 腾讯云COS region
*/
private String qRegion;
/**
* 腾讯云COS qEndpoint
*/
private String qEndpoint;

/**
* 腾讯云COS qEndpointExternal
*/
private String qEndpointExternal;

/**
* COSClient
*/
private COSClient cosClient;

public TencentCOSUploadUtil(String basedir, String qAccessKey, String qSecretKey, String qBucket, String qRegion, String qEndpoint, String qEndpointExternal) {
super(basedir);
this.qAccessKey = qAccessKey;
this.qSecretKey = qSecretKey;
this.qBucket = qBucket;
this.qRegion = qRegion;
this.qEndpoint = qEndpoint;
this.qEndpointExternal = qEndpointExternal;
}

@Override
protected String upload(File tempFile, String realName) {
initClient();
cosClient.putObject(qBucket,realName,tempFile);
URL url =cosClient.generatePresignedUrl(qBucket, realName, new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100));
String urlString = String.valueOf(url).split("\\?")[0];
logger.info("腾讯云COS上传服务------图片内网url:[{}]", urlString);
urlString = urlString.replaceAll(qEndpoint, qEndpointExternal);
logger.info("腾讯云COS上传服务------图片外网url:[{}]", urlString);
return urlString;
}

@Override
String upload(MultipartFile file) {
initClient();
String key = generateUploadFileName(file);
try (InputStream is = new ByteArrayInputStream(file.getBytes())) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentEncoding(StandardCharsets.UTF_8.name());
metadata.setContentLength(file.getSize());
metadata.setContentType(file.getContentType());
// 上传
cosClient.putObject(qBucket,key, is, metadata);
URL url = cosClient.generatePresignedUrl(qBucket, key, new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100));
String urlString = String.valueOf(url).split("\\?")[0];
logger.info("腾讯云COS上传服务------图片内网url:[{}]", urlString);
urlString = urlString.replaceAll(qEndpoint, qEndpointExternal);
logger.info("腾讯云COS上传服务------图片外网url:[{}]", urlString);
return urlString;
}catch (IOException e){
logger.error("使用腾讯云COS上传文件出现异常",e);
throw new RuntimeException(e);
}
}

@Override
protected String upload(byte[] bytes, String contentType) {
initClient();
String realName = UUID.randomUUID().toString() + ".jpg";
try (InputStream is = new ByteArrayInputStream(bytes)) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentEncoding(StandardCharsets.UTF_8.name());
metadata.setContentLength(is.available());
metadata.setContentType(contentType);
// 上传
cosClient.putObject(qBucket,realName, is, metadata);
URL url = cosClient.generatePresignedUrl(qBucket, realName, new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100));
String urlString = String.valueOf(url).split("\\?")[0];
logger.info("腾讯云COS上传服务------图片内网url:[{}]", urlString);
urlString = urlString.replaceAll(qEndpoint, qEndpointExternal);
logger.info("腾讯云COS上传服务------图片外网url:[{}]", urlString);
return urlString;
}catch (IOException e){
logger.error("使用腾讯云COS上传文件出现异常",e);
throw new RuntimeException(e);
}
}

/**
* @Description: 初始化COSCilent
* @Date: 2019/6/2 9:42 AM
* @Params: []
* @Return: void
*/
@Override
protected void initClient() {
if(cosClient==null){
COSCredentials cosCredentials = new BasicCOSCredentials(qAccessKey,qSecretKey);
ClientConfig clientConfig = new ClientConfig(new Region(qRegion));
cosClient = new COSClient(cosCredentials,clientConfig);
}
}

/**
* shutdown Client
*/
public void shutdown(){
cosClient.shutdown();
}
}

用到的相关工具类如下:

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
/**
* base64字符串转换成图片
* 对字节数组字符串进行Base64解码并生成图片
* @param imgStr base64字符串
* @param imgFilePath 图片存放路径
* @return
**/
public static boolean Base64ToImage(String imgStr,String imgFilePath) {
// 图像数据为空
if (StringUtils.isEmpty(imgStr)) {
return false;
}
//如果包含 data:image/jpeg;base64, 前缀需要去掉
if(imgStr.contains(",")){
imgStr = imgStr.split(",")[1];
}
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
// 调整异常数据
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}

结合SpringBoot,引入自动配置,生成相关上传Bean,如下:

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
@Configuration
public class OssUtilsConfiguration {
@Value("${file.cache.dir}")
private String basedir;

@Value("${file.upload.server.type}")
private String uploadServerType;

@Autowired
private Environment environment;

/**
* 亚马逊S3配置
*/
private String s3accessKey;
private String s3secretKey;
private String s3endpoint;
private String s3bucket;

/**
* 阿里云OSS配置
*/
private String aliyunAccessKey;
private String aliyunSecretKey;
private String aliyunBucket;
private String aliyunEndpoint;
private String aliyunEndpointexternal;

/**
* 微软Azure配置
*/
private String azureAccountName;
private String azureAccountKey;
private String azureEndpointSuffix;
private String azureContainerName;

/**
* 腾讯云COS配置
*/
private String qAccessKey;
private String qSecretKey;
private String qBucket;
private String qRegion;
private String qEndpoint;
private String qEndpointExternal;

/**
* 根据配置的 file.upload.server.type 选择一个上传服务器
* @return
*/
@Bean
public UploadAbstractUtil uploadAbstractUtil(){
//可以根据枚举进行配置 使用阿里云或者亚马逊S3或者Azure
UploadServerEnum uploadServerEnum = UploadServerEnum.getEnum(uploadServerType);
UploadAbstractUtil uploadAbstractUtil;
switch (uploadServerEnum){
//亚马逊s3
case AMAZON:
s3accessKey = environment.getRequiredProperty("s3.accessKey");
s3secretKey = environment.getRequiredProperty("s3.secretKey");
s3endpoint = environment.getRequiredProperty("s3.endpoint");
s3bucket = environment.getRequiredProperty("s3.bucket");
uploadAbstractUtil = new AmazonS3UploadUtil(basedir,s3accessKey,s3secretKey,s3endpoint,s3bucket);
return uploadAbstractUtil;
//阿里云OSS
case ALIOSS:
aliyunAccessKey = environment.getRequiredProperty("aliyun.accessKey");
aliyunSecretKey = environment.getRequiredProperty("aliyun.secretKey");
aliyunBucket = environment.getRequiredProperty("aliyun.bucket");
aliyunEndpoint = environment.getRequiredProperty("aliyun.endpoint");
aliyunEndpointexternal = environment.getRequiredProperty("aliyun.endpointexternal");
uploadAbstractUtil = new AliOssUploadUtil(basedir,aliyunAccessKey,aliyunSecretKey,aliyunEndpoint,aliyunEndpointexternal,aliyunBucket);
return uploadAbstractUtil;
//微软Azure
case AZURE:
azureAccountName = environment.getRequiredProperty("azure.accountName");
azureAccountKey = environment.getRequiredProperty("azure.accountKey");
azureEndpointSuffix = environment.getRequiredProperty("azure.endpointSuffix");
azureContainerName = environment.getRequiredProperty("azure.containerName");
uploadAbstractUtil = new AzureUploadUtil(basedir,azureAccountName,azureAccountKey,azureEndpointSuffix,azureContainerName);
return uploadAbstractUtil;
case TENCENTCOS:
qAccessKey = environment.getRequiredProperty("tencent.accessKey");
qSecretKey = environment.getRequiredProperty("tencent.secretKey");
qBucket = environment.getRequiredProperty("tencent.bucket");
qEndpoint = environment.getRequiredProperty("tencent.endpoint");
qRegion = environment.getRequiredProperty("tencent.region");
qEndpointExternal = environment.getRequiredProperty("tencent.endpointexternal");
uploadAbstractUtil = new TencentCOSUploadUtil(basedir,qAccessKey,qSecretKey,qBucket,qRegion,qEndpoint,qEndpointExternal);
return uploadAbstractUtil;
default:
throw new RuntimeException("暂不支持其他类型的云上传!!!");
}
}
}

UploadServerEnum 枚举如下:

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
public enum  UploadServerEnum {
/**
* 阿里云OSS
*/
ALIOSS("aliyun_oss","阿里云OSS"),
/**
* 亚马逊s3
*/
AMAZON("amazon_s3","亚马逊S3"),
/**
* 微软azure
*/
AZURE("azure","微软Azure"),
/**
* 腾讯云cos
*/
TENCENTCOS("tencent_cos","腾讯云cos");

private String value;
private String desc;

UploadServerEnum(String value, String desc) {
this.value = value;
this.desc = desc;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

public String getDesc() {
return desc;
}

public void setDesc(String desc) {
this.desc = desc;
}

/**
* 获取一个枚举
* @param value
* @return
*/
public static UploadServerEnum getEnum(String value){
return Arrays.stream(UploadServerEnum.values()).filter(e->e.value.equals(value)).findFirst().get();
}
}

我们看到代码比较多……

其实几种云上传的核心只要理解,便非常清楚了。它们的大致步骤如下:

  1. 根据配置信息创建上传client
  2. 上传文件(有多种方式,直接上传文件或根据文件流来上传等)
  3. 上传结果,获取上传文件路径等等。
  4. 如需关闭client,需要关闭client。

总结

通过学习如何进行文件云上传,我们掌握了云上传的方法,也可以体验到一些封装、继承、多态的好处,总的来说是蛮不错的一次体验。

项目地址: ossutils-spring-boot




-------------文章结束啦 ~\(≧▽≦)/~ 感谢您的阅读-------------

您的支持就是我创作的动力!

欢迎关注我的其它发布渠道