在工作中一般都会用到图片上传,并且也不会直接将图片存储在Linux服务器上,这时候就可以存储在云盘里,这里以腾讯云存储桶为例:
- 在pom文件中导入如下依赖
<!--腾讯云存储-->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.2.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
- 在配置文件中配置腾讯云存储桶的相关信息,两种配置方法 yml 和 properties
- [ ] yml配置
server:
port: 8899
tomcat:
uri-encoding: utf-8
servlet:
context-path: /
session:
timeout: 24h
multipart:
max-request-size: 10MB
max-file-size: 10MB
# ============================== MySQL配置 =============================================================================
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/shop_system?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
username: root
password: root
driverClassName: com.mysql.cj.jdbc.Driver
# =================================================== 腾讯云存储配置 ====================================================
tengxun:
accessKey: AKIDFNbZMyWth5wqkihknkikRnwph2ZzoSgDwQ
secretKey: 2HH3hGf0B79xVhelloiukjskjikarGXr
bucket: hello-1266930663
bucketName: hello-1266930663
path: https://hello-1266930663.cos.ap-beijing.myqcloud.com/
qianzhui: lover
area: ap-beijing
- [ ] properties配置
server.servlet.session.timeout=24h
# 上传文件总的最大值
spring.servlet.multipart.max-request-size=10MB
# 单个文件的最大值
spring.servlet.multipart.max-file-size=10MB
# =================================================== 腾讯云存储配置 ====================================================
# 腾讯云存储配置
spring.tengxun.accessKey=AKIDFNbZMyWth5wqkihknkikRnwph2ZzoSgDwQ
spring.tengxun.secretKey=2HH3hGf0B79xVhelloiukjskjikarGXr
spring.tengxun.bucket=hello-1266930663
spring.tengxun.bucketName=hello-1266930663
spring.tengxun.path=https://hello-1266930663.cos.ap-beijing.myqcloud.com/
spring.tengxun.qianzhui=lover
spring.tengxun.area=ap-beijing
- 创建腾讯云的工具类 TencentUtil.java, 下面提供两种读取配置文件的方法:
- [ ] 通过 @ConfigurationProperties(value = "spring.tengxun") 读取配置
//省略 getter 和 setter 方法
@Component
@ConfigurationProperties(value = "spring.tengxun")
public class TencentUtil {
private String accessKey;
private String secretKey;
private String bucket;
private String bucketName;
private String path;
private String qianzhui;
private String area;
public COSClient tencentStart(){
System.out.println(accessKey);
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
ClientConfig clientConfig = new ClientConfig(new Region(area));
// 3 生成cos客户端
COSClient cosClient = new COSClient(cred, clientConfig);
return cosClient;
}
}
- [ ] 直接通过 @Value("${spring.tengxun.xxx}") 的方式读取
//省略 getter 和 setter 方法
@Component
public class TencentUtil {
@Value("${spring.tengxun.accessKey}")
private String accessKey;
@Value("${spring.tengxun.secretKey}")
private String secretKey;
@Value("${spring.tengxun.bucket}")
private String bucket;
@Value("${spring.tengxun.bucketName}")
private String bucketName;
@Value("${spring.tengxun.path}")
private String path;
@Value("${spring.tengxun.qianzhui}")
private String qianzhui;
@Value("${spring.tengxun.area}")
private String area;
public COSClient tencentStart(){
System.out.println(accessKey);
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
ClientConfig clientConfig = new ClientConfig(new Region(area));
// 3 生成cos客户端
COSClient cosClient = new COSClient(cred, clientConfig);
return cosClient;
}
}
- 创建控制层 uploadController.java 开始上传图片
//@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class UploadController {
// private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);
// 问题:在一个工具类中,通过@Value来映射配置文件的值,得到的总是null
// 原因:不能用new工具类的方式,应该是用容器注册(@Autowried)的方式使用此工具类,就能得到配置文件里的值
@Autowired
private TencentUtil tencentUtil;//不能通过new来调用
/**
* markdown图片上传到腾讯云
* @param file
* @return
*/
@PostMapping("/uploadImage")
public Result uploadImage(@RequestParam("file") MultipartFile file){
System.out.println(file.getContentType().substring(6));// image/png
if (file.isEmpty()) {
return new Result(500,"上传失败,请选择文件");
}
COSClient cosClient = tencentUtil.tencentStart();
// bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
String bucketName = tencentUtil.getBucketName();
// 指定要上传到 COS 上对象键
// 对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名 `bucket1-1250000000.cos.ap-beijing.myqcloud.com/mydemo.jpg` 中,对象键为 mydemo.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
String key = tencentUtil.getQianzhui() + "/"+ tencentUtil.getQianzhui()+ "_" + UUIDUtil.getUUID() + "." + file.getContentType().substring(6);
File localFile = null;
try {
//将 MultipartFile 类型 转为 File 类型
localFile = File.createTempFile("temp",null);
file.transferTo(localFile);
}catch (IOException e){
return new Result(500,e.getMessage());
}
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
Map<String,String> map = new HashMap <>();
map.put("url",tencentUtil.getPath()+key);
return new Result(map);
}
}
- 前端调用上传图片接口
let fd = new FormData();
fd.append('file',file);
this.$http.post("http://localhost:8899/uploadImage", fd,
{
headers:{
'Content-Type': "multipart/form-data",
}
}
).then((res)=>{
if (res.data.code == 200) {
console.log(res,">>>>")
this.imageUrl = res.data.data.url;
}else {
this.$message({
message: res.data.msg,
type: 'error'
});
}
}).catch(function (err) {
console.log("table", err)
});
OK,大功告成,可以使劲的作了。。。。
网友评论