TCCOSController腾讯云COS对象存储java-api

<!--腾讯云cos-->
<dependency>
	<groupId>com.qcloud</groupId>
	<artifactId>cos_api</artifactId>
	<version>5.6.8</version>
</dependency>
package com.irun2u.reggie.controller;

import com.irun2u.reggie.common.R;
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.model.*;
import com.qcloud.cos.region.Region;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @Author: haifei
 * @Date: 2023/1/17 16:41
 *
 * https://cloud.tencent.com/document/product/436/65935
 * https://blog.csdn.net/qq_40801987/article/details/120229835
 * https://blog.csdn.net/mykingblueblue/article/details/126262452
 * https://blog.csdn.net/qq_45498432/article/details/126153116
 */
@Slf4j
@RestController
@RequestMapping("/common")
@Api(tags = "腾讯云COS接口(在线图床)")
public class TCCOSController {

    @Value("${spring.tengxun.SecretId}")
    private String secretId;

    @Value("${spring.tengxun.SecretKey}")
    private String secretKey;

    @Value("${spring.tengxun.region}")
    private String region;

    @Value("${spring.tengxun.bucketName}")
    private String bucketName;


    public COSClient initClient(){
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(this.secretId, this.secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }


    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("[图片]文件上传")
    public R<String> upload(MultipartFile file){
        log.info("文件:{}", file.toString());
        //从原始文件名获取后缀名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名,防止上传文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix; //key
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, "img/reggie/"+ fileName, file.getInputStream(), objectMetadata);
            COSClient cosClient = initClient();
            cosClient.putObject(putObjectRequest);
            cosClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead); // 设置权限(公开读)
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.success(fileName); //前端新增菜品时需要保存对应文件名到数据库
    }


    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    @ApiOperation("[图片]文件下载")
    public void download(String name, HttpServletResponse response){
        response.setContentType("image/jpeg");
        COSObjectInputStream cosObjectInput = null;
        ServletOutputStream outputStream = null;
        try {
            //通过输入流读取文件内容
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, "img/reggie/" + name);
            COSObject cosObject = initClient().getObject(getObjectRequest);
            cosObjectInput = cosObject.getObjectContent();
            //通过输出流将文件写回浏览器以展示
            outputStream = response.getOutputStream();
            //执行读写
            int len = 0;
            byte[] bytes = new byte[1024];
            while ( (len = cosObjectInput.read(bytes)) != -1 ){
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(cosObjectInput);
            IOUtils.closeQuietly(outputStream);
        }
    }

}


参考本地文件上传下载

package com.irun2u.reggie.controller;

import com.irun2u.reggie.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: haifei
 * @Date: 2023/1/13 9:53
 */
@Slf4j
@RestController
//@RequestMapping("/common")
@Api(tags = "文件处理通用接口(本地图床已弃用)")
public class CommonController {

    /**
     * yml配置文件中自定义的数据通过@Value获取
     */
    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("[图片]文件上传")
    public R<String> upload(MultipartFile file){ //参数名file必须与前端input标签中name的属性值保持一致
        log.info("文件:{}", file.toString());
        //从原始文件名获取后缀名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名,防止上传文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;
        //判断当前目录是否存在,不存在的话就创建
        File dir = new File(basePath); //File既可以是文件也可以是目录对象
        if (!dir.exists()){
            dir.mkdirs();
        }
        try {
            //file是一个临时文件,需要转存到自定义的指定位置,否则本地请求完成后临时文件会被删除
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName); //前端新增菜品时需要保存对应文件名到数据库
    }


    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    @ApiOperation("[图片]文件下载")
    public void download(String name, HttpServletResponse response){
        response.setContentType("image/jpeg");
        FileInputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            //通过输入流读取文件内容
            inputStream = new FileInputStream(new File(basePath + name));
            //通过输出流将文件写回浏览器以展示
            outputStream = response.getOutputStream();
            //执行读写
            int len = 0;
            byte[] bytes = new byte[1024];
            while ( (len = inputStream.read(bytes)) != -1 ){
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
//            inputStream.close();
//            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    }

}

posted @ 2023-02-01 16:36  yub4by  阅读(48)  评论(0编辑  收藏  举报