yupeng
2025-03-05 86abfc7d0a96f627853273256db4bfb501b866da
ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TencentCosUtil.java
@@ -60,7 +60,7 @@
    /**
     * 上传文件,并存入sys_file,返回文件的主键ID
     * @param file
     * @param folder
     * @param folder  格式:/xxxxx,/xxxx/xxxx ,最后不用加斜杠
     * @return
     */
    public TFile upload(MultipartFile file, String folder){
@@ -75,12 +75,11 @@
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            //使用UUID工具  创建唯一名称,放置文件重名被覆盖,在拼接上上命令获取的文件类型
            String fileName = UUID.randomUUID() + fileType;
            String name = (StringUtils.isNotEmpty(folder)?
            String filePath = (StringUtils.isNotEmpty(folder)?
                    folder+"/"
                    :"/default/") + DateUtil.format(new Date(),NORM_DATE_FORMAT)+"/"+fileName;
            // 指定文件上传到 COS 上的路径,即对象键。最终文件会传到存储桶名字中的images文件夹下的fileName名字
            String key = cosConfig.getLocation()+"/" + fileName;
            filePath = cosConfig.getLocation() + filePath;
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // - 使用输入流存储,需要设置请求长度
@@ -90,12 +89,12 @@
            // - 设置Content-Type
            objectMetadata.setContentType(fileType);
            //上传文件
            cosClient.putObject(cosConfig.getBucketName(), key, inputStream, objectMetadata);
            cosClient.putObject(cosConfig.getBucketName(), filePath, inputStream, objectMetadata);
            TFile tFile = new TFile();
            tFile.setFileName(name);
            tFile.setFileName(filePath);
            tFile.setRealName(originalFilename);
            tFile.setFileType(fileType);
            tFile.setUrl(cosConfig.getRootSrc()+key);
            tFile.setUrl(cosConfig.getRootSrc()+filePath);
            tFile.setContentType(file.getContentType());
            tFile.setFileSize(file.getSize());
            sysFileService.save(tFile);
@@ -113,7 +112,7 @@
     * @param file
     * @return 返回文件的浏览全路径
     */
    public String upLoadFile(MultipartFile file) {
    public String upLoadFile(MultipartFile file,String folder) {
        try {
            // 获取上传的文件的输入流
            InputStream inputStream = file.getInputStream();
@@ -124,7 +123,11 @@
            //使用UUID工具  创建唯一名称,放置文件重名被覆盖,在拼接上上命令获取的文件类型
            String fileName = UUID.randomUUID() + fileType;
            // 指定文件上传到 COS 上的路径,即对象键。最终文件会传到存储桶名字中的images文件夹下的fileName名字
            String key = cosConfig.getLocation()+"/" + 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();
            // - 使用输入流存储,需要设置请求长度
@@ -134,9 +137,9 @@
            // - 设置Content-Type
            objectMetadata.setContentType(fileType);
            //上传文件
            PutObjectResult putResult = cosClient.putObject(cosConfig.getBucketName(), key, inputStream, objectMetadata);
            PutObjectResult putResult = cosClient.putObject(cosConfig.getBucketName(), filePath, inputStream, objectMetadata);
            // 创建文件的网络访问路径
            String url = cosConfig.getRootSrc() + key;
            String url = cosConfig.getRootSrc() + filePath;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
@@ -155,15 +158,6 @@
        HttpServletResponse response = WebUtils.response();
        String replace = file.replace(cosConfig.getRootSrc(), "");
        response.setHeader("Access-Control-Expose-Headers","File-Type");
        COSCredentials cred = new BasicCOSCredentials(
                cosConfig.getSecretId(),
                cosConfig.getSecretKey());
        // 2.1 设置存储桶的地域(上文获得)
        Region region = new Region(cosConfig.getBucketAddr());
        ClientConfig clientConfig = new ClientConfig(region);
        // 2.2 使用https协议传输
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        try {
            // 5. 下载文件并获取输入流
            InputStream inputStream = cosClient.getObject(cosConfig.getBucketName(), replace).getObjectContent();
@@ -184,15 +178,6 @@
    public String downLoadFileImg(String file) {
        byte[] data = null;
        String replace = file.replace(cosConfig.getRootSrc(), "");
        COSCredentials cred = new BasicCOSCredentials(
                cosConfig.getSecretId(),
                cosConfig.getSecretKey());
        // 2.1 设置存储桶的地域(上文获得)
        Region region = new Region(cosConfig.getBucketAddr());
        ClientConfig clientConfig = new ClientConfig(region);
        // 2.2 使用https协议传输
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        try {
            // 5. 下载文件并获取输入流
            InputStream inputStream = cosClient.getObject(cosConfig.getBucketName(), replace).getObjectContent();
@@ -213,22 +198,39 @@
        return Base64.getEncoder().encodeToString(data);
    }
    public void download(TFile file) {
    public void download(String fileUrl) {
        HttpServletResponse response = WebUtils.response();
        COSCredentials cred = new BasicCOSCredentials(
                cosConfig.getSecretId(),
                cosConfig.getSecretKey());
        // 2.1 设置存储桶的地域(上文获得)
        Region region = new Region(cosConfig.getBucketAddr());
        ClientConfig clientConfig = new ClientConfig(region);
        // 2.2 使用https协议传输
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        fileUrl = fileUrl.replace(cosConfig.getRootSrc(), "");
            // 5. 下载文件并获取输入流
        COSObject object = cosClient.getObject(cosConfig.getBucketName(), file.getUrl());
        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");
@@ -244,4 +246,6 @@
            log.error("读取cos图片发生异常", e);
        }
    }
}