最近在做一个项目,涉及到腾讯云上传文件/图片到服务器,为了图方便并且提升访问速度,想着上传到腾讯云存储桶是一个不错的选择。腾讯云存储桶的创建可见我之前的文章。
当然存储桶里面不仅可以存图片,也可以存储其它文件、视频,甚至整个博客静态文件都可以存储进行访问。
添加依赖
首先我们在 SpringBoot 的依赖中添加:
com.qcloud
cos_api
5.4.10
org.slf4j
slf4j-log4j12
然后我们在 SpringBoot 的配置文件 application.yml 中添加配置信息:
# 腾讯云地址
tencent:
path: https://forum-xxxxxxxx.cos.ap-/
上面的路径就是你访问的存储桶域名
编写文件上传控制器工具类
一般项目中是存在一个 utils 工具类包的,我们在其中新建一个文件上传的工具类,代码如下。其中需要我们填写 bucketName、secretId 和 secretkey 三个字段,
这三个字段来源均参考上述使用「 腾讯云存储博客图片」 一文中详解。
这三个字段也可以写在配置文件中,然后使用 SpringBoot 的@Value属性注入字段。不建议像下文一样写在代码中。
package cn.bestzuo.zuoforum.util;
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.model.*;
import com.qcloud.cos.region.Region;
import java.io.File;
import java.util.Random;
/**
* 腾讯云对象存储
*/
public class TencentCOS {
// 此处填写的存储桶名称
private static final String bucketName = "forum-12xxxx558";
// secretId
private static final String secretId = "xxxx";
// secretKey
private static final String secretKey = "xxxx";
// 1 初始化用户身份信息(secretId, secretKey,可在腾讯云后台中的API密钥管理中查看!
private static COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置bucket的区域, COS地域的简称请参照
// /document/product/436/6224,根据自己创建的存储桶选择地区
private static ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
/**
* 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口 大文件上传请参照 API 文档高级 API 上传
*
* @param localFile 要上传的文件
*/
public static String uploadfile(File localFile,String pathPrefix) throws CosClientException, CosServiceException {
// 生成cos客户端
COSClient cosclient = new COSClient(cred, clientConfig);
String fileName = "";
try {
fileName = localFile.getName();
String substring = fileName.substring(fileName.lastIndexOf("."));
Random random = new Random();
// 指定要上传到 COS 上的路径
fileName = pathPrefix + "/" + random.nextInt(10000) + System.currentTimeMillis() + substring;
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, localFile);
PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭客户端(关闭后台线程)
cosclient.shutdown();
}
return fileName;
}
/**
* 下载文件
*/
public static void downFile() {
// 生成cos客户端
COSClient cosclient = new COSClient(cred, clientConfig);
//要下载的文件路径和名称
String key = "down/demo1.jpg";
// 指定文件的存储路径
File downFile = new File("src/test/resources/mydown.txt");
// 指定要下载的文件所在的 bucket 和对象键
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
ObjectMetadata downObjectMeta = cosclient.getObject(getObjectRequest, downFile);
}
/**
* 删除文件
*/
public static void deletefile(String key) throws CosClientException, CosServiceException {
// 生成cos客户端
COSClient cosclient = new COSClient(cred, clientConfig);
// 指定要删除的 bucket 和路径
cosclient.deleteObject(bucketName, key);
// 关闭客户端(关闭后台线程)
cosclient.shutdown();
}
}
添加 Controller 类
然后我们就可以创建一个 Controller 类进行调用了,以下是一个上传图片控制器类,也可以根据自己需求进行修改,注释都写在代码中了。
package cn.bestzuo.zuoforum.controller;
import cn.mon.ForumResult;
import cn.mon.LayEditUploadImageResult;
import cn.mon.WangEditorResult;
import cn.bestzuo.zuoforum.pojo.UploadImage;
import cn.bestzuo.zuoforum.service.UserInfoService;
import cn.bestzuo.zuoforum.util.TencentCOS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 图片上传Controller
*/
@Controller
public class ImageUploadController {
@Value("${tencent.path}")
private String IMAGE_PATH;
@Autowired
private UserInfoService userInfoService;
/**
* 上传头像
*/
@RequestMapping("/upload")
@ResponseBody
public ForumResult upload(@RequestParam("file") MultipartFile multipartFile, @RequestParam("username") String username, Model model) throws Exception {
//获取文件的名称
String fileName = multipartFile.getOriginalFilename();
//判断有无后缀
if (fileName.lastIndexOf(".") < 0)
return new ForumResult(500, "上传图片格式不正确", null);
//获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
//如果不是图片
if (!prefix.equalsIgnoreCase(".jpg") && !prefix.equalsIgnoreCase(".jpeg") && !prefix.equalsIgnoreCase(".svg") && !prefix.equalsIgnoreCase(".gif") && !prefix.equalsIgnoreCase(".png")) {
return new ForumResult(500, "上传图片格式不正确", null);
}
//使用uuid作为文件名,防止生成的临时文件重复
final File excelFile = File.createTempFile("imagesFile-" + System.currentTimeMillis(), prefix);
//将Multifile转换成File
multipartFile.transferTo(excelFile);
//调用腾讯云工具上传文件
String imageName = TencentCOS.uploadfile(excelFile, "avatar");
//程序结束时,删除临时文件
deleteFile(excelFile);
//存入图片名称,用于网页显示
model.addAttribute("imageName", imageName);
//更新数据库
userInfoService.updateUserAvatar(imageName, username);
//返回成功信息
return new ForumResult(200, "头像更换成功", imageName);
}
/**
* 删除临时文件
*
* @param files 临时文件,可变参数
*/
private void deleteFile(File... files) {
for (File file : files) {
if (file.exists()) {
file.delete();
}
}
}
}
如果觉得《上传excel腾讯云服务器 使用SpringBoot上传文件到腾讯云》对你有帮助,请点赞、收藏,并留下你的观点哦!