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); } } }