官方文档:https://cloud.tencent.com/document/product/436/10199

首先导入依赖

1
2
3
4
5
6
7
8
9
10
11
12
<!--腾讯云cos相关依赖-->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.89</version>
</dependency>
<!--接收文件-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

创建一个 FileServer 类,处理上传逻辑

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
package com.szx.boot03tengxunyun.server;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.szx.boot03tengxunyun.bean.CosBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* @author songzx
* @create 2022-07-19 11:28
*/
@Service
public class FileServer {
// 1 初始化用户身份信息(secretId, secretKey)。
// SECRETID和SECRETKEY请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
String secretId = "";
String secretKey = "";
String filePath = "https://szx-bucket1.oss-cn-hangzhou.aliyuncs.com/"; // 文件基础路径
String bucketName = "blogimages-1257342648"; // 指定文件将要存放的存储桶

COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
Region region = new Region("ap-shanghai"); // ap-shanghai 表示上海
ClientConfig clientConfig = new ClientConfig(region);

public String upload(MultipartFile multipartFile) throws IOException {
String filename = multipartFile.getOriginalFilename();
// 这里建议设置使用 https 协议
// 从 5.6.54 版本开始,默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);
// 3 生成 cos 客户端。
COSClient cosClient = new COSClient(cred, clientConfig);

//这里文件名用了当前时间 防止重复,可以根据自己的需要来写
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String[] fileNames= filename.split("\\.");
String name = fileNames[0]+ sdf.format(new Date())+ filename.substring(filename.lastIndexOf("."), filename.length());
// 指定文件上传到 COS 上的路径,即对象键。例如对象键为folder/picture.jpg,则表示将文件 picture.jpg 上传到 folder 路径下
String key = "javaUpload/" + name;
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, multipartFile.getInputStream(),null);
// 执行上传方法
cosClient.putObject(putObjectRequest);
// 返回线上地址
return filePath + key;
}
}

封装一个 msg 类,用来返回上传成功返回的数据信息

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
package com.szx.boot03tengxunyun.bean;

import java.util.HashMap;

/**
* @author songzx
* @create 2022-07-19 15:36
*/
public class Msg {
int code; // 接口响应状态码,500 异常,200 OK
String message; // 接口返回的信息
HashMap<String,Object> data = new HashMap<>(); // 接口实际返回的内容

/**
* 接口成功返回方法
* @author Songzx
* @date 2022/7/2
*/
public static Msg success(){
Msg msg = new Msg();
msg.setCode(200);
msg.setMessage("成功");
return msg;
}

/**
* 接口失败返回方法
* @author Songzx
* @date 2022/7/2
*/
public static Msg error(){
Msg msg = new Msg();
msg.setCode(500);
msg.setMessage("失败");
return msg;
}

/**
* 可以链式调用的add方法
* @author Songzx
* @date 2022/7/2
*/
public Msg add(String key,Object data){
this.getData().put(key,data);
return this;
}

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public HashMap<String, Object> getData() {
return data;
}

public void setData(HashMap<String, Object> data) {
this.data = data;
}

public Msg(int code, String message, HashMap<String, Object> data) {
this.code = code;
this.message = message;
this.data = data;
}

public Msg() {
}
}

编写一个 FileController,调用 FileServer 中的 upload 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RestController
public class FileController {
@Autowired
FileServer fileServer;

@RequestMapping(value = "/upload",method = RequestMethod.POST)
// 这里接收到的 file 名称是前端传递过来的文件参数名称
public Msg uploadFile(@RequestParam("file") MultipartFile multipartFile){
try {
String filePath = fileServer.upload(multipartFile);
return Msg.success().add("fileUrl",filePath);
} catch (IOException e) {
e.printStackTrace();
}
return Msg.error();
}
}

然后前端通过 post 方式调用 /upload 接口,同时传递文件过来。前端代码如下,使用了 ElementUI 中的文件上传组件

1
2
3
4
5
6
7
8
<template>
<div>
<el-upload class="upload-demo" drag action="/upload" multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>
</div>
</template>

运行效果:

Snipaste_2022-07-19_16-04-15.png

登录腾讯云控制台,访问对象存储模块,查看 javaUpload 文件夹下的内容

Snipaste_2022-07-19_16-09-11.png

可以看到文件成功上传到云端