目录
准备工作
Java代码编写
控制台打印
整理成工具类
编写接口
Postman测试
准备工作
1.进入网址
腾讯云 产业智变·云启未来 - 腾讯 (tencent.com)
2.搜索cos,点击立即使用,刚开始会免费赠送你
3.存储都是基于桶的,先创建桶,在桶里面创建文件夹,所以点击创建桶
4.查看桶列表,点击左侧
5.点进去,创建文件夹,我这里创建了两个文件夹
6.桶搞完了,要拿到 secretId secretKey,进入下面的地址
登录 - 腾讯云
点击新建密钥,创建自己的密钥
以上准备工作就做完了,下面进行代码测试
Java代码编写
package com.zsp.quartz.util.OSS;
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 java.io.File;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;
public class getOSSToken {
public static void main(String[] args) {
// 初始化客户端
String secretId = "xxxxxx";
String secretKey = "xxxxxx";
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
Region region = new Region("ap-nanjing");
ClientConfig clientConfig = new ClientConfig(region);
clientConfig.setHttpProtocol(HttpProtocol.https);
COSClient cosClient = new COSClient(cred, clientConfig);
//定义存储桶
String bucket = "zsp-image-xxxxxx"; //存储桶名称,格式:BucketName-APPID
// 上传文件
File localFile = new File("C:/Users/UU/Desktop/我的/生活照.jpeg");
// 指定文件上传到 COS 上的路径,即对象键。
String path = "image/"+ LocalDateTime.now() +"file"+ UUID.randomUUID()+".jpeg";
// 三个参数:桶名,文件夹路径,文件
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, path, localFile);
System.out.println("key为:"+putObjectRequest.getKey()); // image/2023-10-18T11:58:25.792fileef9bb4a9-3b0a-49f1-92a4-5bc3f3572977.jpeg
// 上传到oss
cosClient.putObject(putObjectRequest);
// 得到图片地址
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// 三个参数:桶名,文件名,过期时间
URL url = cosClient.generatePresignedUrl(bucket, putObjectRequest.getKey(), expiration);
System.out.println(url.toString());
//关闭资源
cosClient.shutdown();
}
}
控制台打印
整理成工具类
package com.zsp.quartz.util.COS;
import cn.hutool.core.date.DateUtil;
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.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Random;
public class COSUpload {
private static String secretId = "asdkhjahsdkjhasjkdhas";
private static String secretKey = "asmdiuoahuihas";
private static String bucket = "zsp-image-xxxxxxxx";
private static String fileFolder = "image/";
private static COSClient cosClient;
static {
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
Region region = new Region("ap-nanjing");
ClientConfig clientConfig = new ClientConfig(region);
clientConfig.setHttpProtocol(HttpProtocol.https);
cosClient = new COSClient(cred, clientConfig);
}
public static String uploadFileToCOS(MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();
String substring;
if (originalFilename.contains(".")) {
substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
} else {
substring = originalFilename;
}
Random random = new Random();
String fileName = random.nextInt(10000) + System.currentTimeMillis() + substring;
InputStream inputStream = null;
inputStream = file.getInputStream();
return uploadFileCOS(inputStream, fileName, fileFolder);
}
public static String uploadFileCOS(InputStream instream, String fileName, String fileFolder) {
String ret = "";
try {
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
if (fileName.contains(".")) {
objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
} else {
objectMetadata.setContentType(getcontentType(fileName));
}
objectMetadata.setContentDisposition("inline;filename=" + fileName);
String filePath = fileFolder + DateUtil.format(new Date(), "yyyy/MM/dd") + "/" + fileName;
// 上传文件
PutObjectRequest data = new PutObjectRequest(bucket, filePath, instream, objectMetadata);
cosClient.putObject(data);
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// 三个参数:桶名,文件名,过期时间
URL url = cosClient.generatePresignedUrl(bucket, data.getKey(), expiration);
ret = url.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
public static String getcontentType(String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase(".bmp")) {
return "image/bmp";
}
if (FilenameExtension.equalsIgnoreCase(".gif")) {
return "image/gif";
}
if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension.equalsIgnoreCase(".jpg")
|| FilenameExtension.equalsIgnoreCase(".png")) {
return "image/jpeg";
}
if (FilenameExtension.equalsIgnoreCase(".html")) {
return "text/html";
}
if (FilenameExtension.equalsIgnoreCase(".txt")) {
return "text/plain";
}
if (FilenameExtension.equalsIgnoreCase(".vsd")) {
return "application/vnd.visio";
}
if (FilenameExtension.equalsIgnoreCase(".pptx") || FilenameExtension.equalsIgnoreCase(".ppt")) {
return "application/vnd.ms-powerpoint";
}
if (FilenameExtension.equalsIgnoreCase(".docx") || FilenameExtension.equalsIgnoreCase(".doc")) {
return "application/msword";
}
if (FilenameExtension.equalsIgnoreCase(".xml")) {
return "text/xml";
}
if (FilenameExtension.equalsIgnoreCase(".pdf")) {
return "application/pdf";
}
return "image/jpeg";
}
}
编写接口
/**
* 图片上传
* @param file
* @return
* @throws Exception
*/
private final static int maxSize = 15 * 1024 * 1024;
@PostMapping("/oss/upload")
public Result<String> uploadFile(@RequestParam("file")MultipartFile file) throws Exception {
//检查文件是否为空
if (file.isEmpty()) return Result.fail("请选择图片");
//检查文件大小
if (file.getSize() > maxSize) return Result.fail("请上传15M以内的图片");
final String url = COSUpload.uploadFileToCOS(file);
ImageResult imageResult = new ImageResult(url);
return Result.success(url);
}
Postman测试
COS服务器显示
按照时间节点创建日期文件夹进行存储。