极简之腾讯云cos上传下载

本文介绍如何使用腾讯云COS SDK进行文件的上传和下载操作,包括配置客户端、实现文件上传并获取上传凭证,以及下载文件的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom文件

        <dependency>
            <groupId>com.qcloud</groupId>
            <artifactId>cos_api</artifactId>
            <version>5.6.38</version>
        </dependency>

Controller

	@RequestMapping(path = "/download", method = RequestMethod.GET)
	public void download(HttpServletRequest request, HttpServletResponse response,  @RequestParam("name") String name) throws IOException {
		try {
			byte[] bytes = cosService.cosDownload(name);
			String extension = StringUtils.substringAfterLast(name, ".").toLowerCase();
			String mime = mimeTypes.getProperty(extension, MIME_DEFAULT);
			response.addHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8") + ";filename*=UTF-8''" + URLEncoder.encode(name, "UTF-8"));
			response.setHeader("Content-Type", mime);
			IOUtils.write(bytes, response.getOutputStream());
			response.getOutputStream().close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			response.sendError(500, e.getMessage());
		}
	}

Service

import com.amazonaws.services.s3.transfer.TransferManager;
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.qcloud.cos.utils.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

/**
 * 腾讯 COS
 * 文件的上传,下载
 */
@Service
public class CosService {

	static TransferManager transferManager = null;
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm ss");

	@Value("${cos.secretId}")
	private String secretId;
	@Value("${cos.secretKey}")
	private String secretKey;
	@Value("${cos.region}")
	private String region;
	@Value("${cos.bucketName}")
	private String bucketName;
	@Value("${cos.appID}")
	private String appId;


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


	public byte[] cosDownload (String name){
		String bName = bucketName+"-"+appId;
		String key = "文件夹名/"+name;
		byte[] data = null;
		COSClient cc = getCosClient();
		GetObjectRequest getObjectRequest = new GetObjectRequest(bName, key);
		COSObject cosObject = cc.getObject(getObjectRequest);
		COSObjectInputStream cosObjectInput = cosObject.getObjectContent();
		try {
			data = IOUtils.toByteArray(cosObjectInput);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 下载对象的 CRC64
		String crc64Ecma = cosObject.getObjectMetadata().getCrc64Ecma();
		try {
			cosObjectInput.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}



	public String uploadFile(MultipartFile file) throws MalformedURLException {
		File f = new File(file.getOriginalFilename());
		int n;
		String etag = null;
		try ( InputStream in  = file.getInputStream(); OutputStream os = new FileOutputStream(f)){
			// 得到文件流。以文件流的方式输出到新文件
			// 可以使用byte[] ss = multipartFile.getBytes();代替while
			byte[] buffer = new byte[4096];
			while ((n = in.read(buffer,0,4096)) != -1){
				os.write(buffer,0,n);
			}
			// 读取文件第一行
			BufferedReader bufferedReader = new BufferedReader(new FileReader(f));
			System.out.println(bufferedReader.readLine());
			// 输出路径
			bufferedReader.close();
		}catch (IOException e){
			e.printStackTrace();
		}
		File localFile = new File(f.getAbsolutePath());
		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName+"-"+appId, "gcore/"+file.getOriginalFilename(), localFile);
		putObjectRequest.setStorageClass(StorageClass.Standard);
		COSClient cc = getCosClient();
		try {
			PutObjectResult putObjectResult = cc.putObject(putObjectRequest);
			etag = putObjectResult.getETag();
			System.out.println(etag);
		} catch (CosServiceException e) {
			e.printStackTrace();
		} catch (CosClientException e) {
			e.printStackTrace();
		}
		// 关闭客户端
		cc.shutdown();
		return etag;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值