yupeng
2025-03-07 7424b29a429d58d511676e045b0928cd97b13973
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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.http.HttpProtocol;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.ruoyi.common.utils.WebUtils;
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;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
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 {
 
    /**
     * 1.调用静态方法getCosClient()就会获得COSClient实例
     * 2.本方法根据永久密钥初始化 COSClient的,官方是不推荐,官方推荐使用临时密钥,是可以限制密钥使用权限,创建cred时有些区别
     *
     * @return COSClient实例
     */
 
    @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;
        }
    }
 
    /**
     * 只要调用静态方法upLoadFile(MultipartFile multipartFile)就可以获取上传后文件的全路径
     *
     * @param file
     * @return 返回文件的浏览全路径
     */
    public String upLoadFile(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;
            // 指定文件上传到 COS 上的路径,即对象键。最终文件会传到存储桶名字中的images文件夹下的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();
            // - 使用输入流存储,需要设置请求长度
            objectMetadata.setContentLength(inputStream.available());
            // - 设置缓存
            objectMetadata.setCacheControl("no-cache");
            // - 设置Content-Type
            objectMetadata.setContentType(fileType);
            //上传文件
            PutObjectResult putResult = 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);
            // 创建文件的网络访问路径
            String url = cosConfig.getRootSrc() + filePath;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件发生异常",e);
            // 发生IO异常、COS连接异常等,返回空
            return null;
        }
    }
 
    /**
     * 下载文件
     * @param file
     * @return
     */
    public void downLoadFile(String file) {
        HttpServletResponse response = WebUtils.response();
        String replace = file.replace(cosConfig.getRootSrc(), "");
        response.setHeader("Access-Control-Expose-Headers","File-Type");
        try {
            // 5. 下载文件并获取输入流
            InputStream inputStream = cosClient.getObject(cosConfig.getBucketName(), replace).getObjectContent();
            ServletOutputStream outputStream = response.getOutputStream();
            // 6. 处理输入流,例如读取内容或保存到本地文件
            // 这里仅作示例,实际应用中需要根据需求处理输入流
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                // 处理读取到的数据
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载文件发生异常",e);
        }
    }
    public String downLoadFileImg(String file) {
        byte[] data = null;
        String replace = file.replace(cosConfig.getRootSrc(), "");
        try {
            // 5. 下载文件并获取输入流
            InputStream inputStream = cosClient.getObject(cosConfig.getBucketName(), replace).getObjectContent();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            // 6. 处理输入流,例如读取内容或保存到本地文件
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                // 处理读取到的数据
                swapStream.write(buffer, 0, len);
            }
            data = swapStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载图片发生异常",e);
        } finally {
        }
        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);
        }
    }
 
 
}