无关风月
2025-03-06 41e05da9a811cd9394ce9bddf5edcb7cde58db06
ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TencentCosUtil.java
@@ -1,20 +1,23 @@
package com.ruoyi.web.controller.tool;
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.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.utils.IOUtils;
import com.ruoyi.common.utils.WebUtils;
import org.springframework.beans.factory.annotation.Value;
import com.ruoyi.system.model.TFile;
import com.ruoyi.system.service.SysFileService;
import com.ruoyi.system.service.impl.SysFileServiceImpl;
import com.ruoyi.web.core.config.FileUploaderConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@@ -25,44 +28,17 @@
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
import static cn.hutool.core.date.DatePattern.NORM_DATE_FORMAT;
/**
 * @author HJL
 */
@Component
@Slf4j
public class TencentCosUtil {
    /**
     * COS的SecretId
     */
    @Value("${cos.client.accessKey}")
    private String secretId;
    /**
     * COS的SecretKey
     */
    @Value("${cos.client.secretKey}")
    private String secretKey;
    /**
     * 文件上传后访问路径的根路径,后面要最佳文件名字与类型
     */
    @Value("${cos.client.rootSrc}")
    private String rootSrc;
    /**
     * 上传的存储桶的地域
     */
    @Value("${cos.client.bucketAddr}")
    private String bucketAddr;
    /**
     * 存储桶的名字,是自己在存储空间自己创建的,我创建的名字是:qq-test-1303******
     */
    @Value("${cos.client.bucket}")
    private String bucketName;
    /**
     * 文件存放位置
     */
    @Value("${cos.client.location}")
    private String location;
    /**
     * 1.调用静态方法getCosClient()就会获得COSClient实例
@@ -70,16 +46,64 @@
     *
     * @return COSClient实例
     */
    private COSClient getCosClient() {
        // 1 初始化用户身份信息(secretId, secretKey)。
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2.1 设置存储桶的地域(上文获得)
        Region region = new Region(bucketAddr);
        ClientConfig clientConfig = new ClientConfig(region);
        // 2.2 使用https协议传输
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 生成 cos 客户端
        return new COSClient(cred, clientConfig);
    @Autowired
    COSClient cosClient;
    @Autowired
    FileUploaderConfig cosConfig;
    @Autowired
    SysFileService sysFileService;
    /**
     * 上传文件,并存入sys_file,返回文件的主键ID
     * @param file
     * @param folder  格式:/xxxxx,/xxxx/xxxx ,最后不用加斜杠
     * @return
     */
    public TFile upload(MultipartFile file, String folder){
        try {
            // 获取上传的文件的输入流
            InputStream inputStream = file.getInputStream();
            // 避免文件覆盖,获取文件的原始名称,如123.jpg,然后通过截取获得文件的后缀,也就是文件的类型
            String originalFilename = file.getOriginalFilename();
            //获取文件的类型
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            //使用UUID工具  创建唯一名称,放置文件重名被覆盖,在拼接上上命令获取的文件类型
            String fileName = UUID.randomUUID() + fileType;
            String filePath = (StringUtils.isNotEmpty(folder)?
                    folder+"/"
                    :"/default/") + DateUtil.format(new Date(),NORM_DATE_FORMAT)+"/"+fileName;
            // 指定文件上传到 COS 上的路径,即对象键。最终文件会传到存储桶名字中的images文件夹下的fileName名字
            filePath = cosConfig.getLocation() + filePath;
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // - 使用输入流存储,需要设置请求长度
            objectMetadata.setContentLength(inputStream.available());
            // - 设置缓存
            objectMetadata.setCacheControl("no-cache");
            // - 设置Content-Type
            objectMetadata.setContentType(fileType);
            //上传文件
            cosClient.putObject(cosConfig.getBucketName(), filePath, inputStream, objectMetadata);
            TFile tFile = new TFile();
            tFile.setFileName(filePath);
            tFile.setRealName(originalFilename);
            tFile.setFileType(fileType);
            tFile.setUrl(cosConfig.getRootSrc()+filePath);
            tFile.setContentType(file.getContentType());
            tFile.setFileSize(file.getSize());
            sysFileService.save(tFile);
            return tFile;
        } catch (Exception e) {
            log.error("上传文件发生异常",e);
            // 发生IO异常、COS连接异常等,返回空
            return null;
        }
    }
    /**
@@ -88,7 +112,7 @@
     * @param file
     * @return 返回文件的浏览全路径
     */
    public String upLoadFile(MultipartFile file) {
    public String upLoadFile(MultipartFile file,String folder) {
        try {
            // 获取上传的文件的输入流
            InputStream inputStream = file.getInputStream();
@@ -99,7 +123,11 @@
            //使用UUID工具  创建唯一名称,放置文件重名被覆盖,在拼接上上命令获取的文件类型
            String fileName = UUID.randomUUID() + fileType;
            // 指定文件上传到 COS 上的路径,即对象键。最终文件会传到存储桶名字中的images文件夹下的fileName名字
            String key = location+"/" + fileName;
            String filePath = (StringUtils.isNotEmpty(folder)?
                    folder+"/"
                    :"/default/") + DateUtil.format(new Date(),NORM_DATE_FORMAT)+"/"+fileName;
            filePath = cosConfig.getLocation()+"/" + filePath;
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // - 使用输入流存储,需要设置请求长度
@@ -109,14 +137,13 @@
            // - 设置Content-Type
            objectMetadata.setContentType(fileType);
            //上传文件
            PutObjectResult putResult = getCosClient().putObject(bucketName, key, inputStream, objectMetadata);
            PutObjectResult putResult = cosClient.putObject(cosConfig.getBucketName(), filePath, inputStream, objectMetadata);
            // 创建文件的网络访问路径
            String url = rootSrc + key;
            //关闭 cosClient,并释放 HTTP 连接的后台管理线程
            getCosClient().shutdown();
            String url = cosConfig.getRootSrc() + filePath;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件发生异常",e);
            // 发生IO异常、COS连接异常等,返回空
            return null;
        }
@@ -129,20 +156,11 @@
     */
    public void downLoadFile(String file) {
        HttpServletResponse response = WebUtils.response();
        String replace = file.replace(rootSrc, "");
        String replace = file.replace(cosConfig.getRootSrc(), "");
        response.setHeader("Access-Control-Expose-Headers","File-Type");
        COSCredentials cred = new BasicCOSCredentials(
                secretId,
                secretKey);
        // 2.1 设置存储桶的地域(上文获得)
        Region region = new Region(bucketAddr);
        ClientConfig clientConfig = new ClientConfig(region);
        // 2.2 使用https协议传输
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        try {
            // 5. 下载文件并获取输入流
            InputStream inputStream = cosClient.getObject(bucketName, replace).getObjectContent();
            InputStream inputStream = cosClient.getObject(cosConfig.getBucketName(), replace).getObjectContent();
            ServletOutputStream outputStream = response.getOutputStream();
            // 6. 处理输入流,例如读取内容或保存到本地文件
            // 这里仅作示例,实际应用中需要根据需求处理输入流
@@ -154,26 +172,15 @@
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7. 关闭输入流
            cosClient.shutdown();
            log.error("下载文件发生异常",e);
        }
    }
    public String downLoadFileImg(String file) {
        byte[] data = null;
        String replace = file.replace(rootSrc, "");
        COSCredentials cred = new BasicCOSCredentials(
                secretId,
                secretKey);
        // 2.1 设置存储桶的地域(上文获得)
        Region region = new Region(bucketAddr);
        ClientConfig clientConfig = new ClientConfig(region);
        // 2.2 使用https协议传输
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        String replace = file.replace(cosConfig.getRootSrc(), "");
        try {
            // 5. 下载文件并获取输入流
            InputStream inputStream = cosClient.getObject(bucketName, replace).getObjectContent();
            InputStream inputStream = cosClient.getObject(cosConfig.getBucketName(), replace).getObjectContent();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            // 6. 处理输入流,例如读取内容或保存到本地文件
            byte[] buffer = new byte[1024];
@@ -185,10 +192,60 @@
            data = swapStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载图片发生异常",e);
        } finally {
            // 7. 关闭输入流
            cosClient.shutdown();
        }
        return Base64.getEncoder().encodeToString(data);
    }
    public void download(String fileUrl) {
        HttpServletResponse response = WebUtils.response();
        fileUrl = fileUrl.replace(cosConfig.getRootSrc(), "");
            // 5. 下载文件并获取输入流
        COSObject object = cosClient.getObject(cosConfig.getBucketName(),fileUrl);
        try (
            InputStream is = object.getObjectContent();
             OutputStream os = response.getOutputStream()
        ) {
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/"));
            response.setContentType(object.getObjectMetadata().getContentType() + ";charset=utf-8");
            String filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.addHeader("Content-Length", "" + object.getObjectMetadata().getContentLength());
            int len = 0;
            byte[] buffer = new byte[2048];
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            log.error("读取cos图片发生异常", e);
        }
    }
    public void download(TFile file) {
        HttpServletResponse response = WebUtils.response();
        // 5. 下载文件并获取输入流
        COSObject object = cosClient.getObject(cosConfig.getBucketName(), file.getFileName());
        try (
                InputStream is = object.getObjectContent();
                OutputStream os = response.getOutputStream()
        ) {
            response.setContentType(file.getContentType() + ";charset=utf-8");
            String filename = new String(file.getRealName().getBytes("UTF-8"), "ISO-8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.addHeader("Content-Length", "" + file.getFileSize());
            int len = 0;
            byte[] buffer = new byte[2048];
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            log.error("读取cos图片发生异常", e);
        }
    }
}