【技術積累】騰訊/阿里雲物件儲存上傳+刪除

自律即自由-發表於2024-09-10

騰訊/阿里雲物件儲存上傳+刪除

  1. 建立儲存桶 (後面會用到 儲存庫名稱、訪問域名、以及region) region(地域和訪問域名)的查詢參考: https://cloud.tencent.com/document/product/436/6224
  2. https://www.aliyun.com/product/oss

常用的阿里雲、騰訊雲

2.建立Api金鑰 (後面會用到 secretId、secretKey)

application.yml

qcloud:
  path: 域名地址
  bucketName: 儲存庫名稱
  secretId: 金鑰生成的secretId
  secretKey: 金鑰生成的secretKey
  region: 地域簡稱
  prefix: /images/

工具類:

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.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 
 * @date 2021/6/6 19:31
 * @role
 */
@Data
public class QCloudCosUtils {
    //API金鑰secretId
    private String secretId;
    //API金鑰secretKey
    private String secretKey;
    //儲存桶所屬地域
    private String region;
    //儲存桶空間名稱
    private String bucketName;
    //儲存桶訪問域名
    private String path;
    //上傳檔案字首路徑(eg:/images/)
    private String prefix;

    /**
     * 上傳File型別的檔案
     *
     * @param file
     * @return 上傳檔案在儲存桶的連結
     */
    public String upload(File file) {
        //生成唯一檔名
        String newFileName = generateUniqueName(file.getName());
        //檔案在儲存桶中的key
        String key = prefix + newFileName;
        //宣告客戶端
        COSClient cosClient = null;
        try {
            //初始化使用者身份資訊(secretId,secretKey)
            COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
            //設定bucket的區域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            //生成cos客戶端
            cosClient = new COSClient(cosCredentials, clientConfig);
            //建立儲存物件的請求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            //執行上傳並返回結果資訊
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return path + key;
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return null;
    }

    /**
     * upload()過載方法
     *
     * @param multipartFile
     * @return 上傳檔案在儲存桶的連結
     */
    public String upload(MultipartFile multipartFile) {
        System.out.println(multipartFile);
        //生成唯一檔名
        String newFileName = generateUniqueName(multipartFile.getOriginalFilename());
        //檔案在儲存桶中的key
        String key = prefix + newFileName;
        //宣告客戶端
        COSClient cosClient = null;
        //準備將MultipartFile型別轉為File型別
        File file = null;
        try {
            //生成臨時檔案
            file = File.createTempFile("temp", null);
            //將MultipartFile型別轉為File型別
            multipartFile.transferTo(file);
            //初始化使用者身份資訊(secretId,secretKey)
            COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
            //設定bucket的區域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            //生成cos客戶端
            cosClient = new COSClient(cosCredentials, clientConfig);
            //建立儲存物件的請求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            //執行上傳並返回結果資訊
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return path + key;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return null;
    }

    /**
     * 根據UUID生成唯一檔名
     *
     * @param originalName
     * @return
     */
    public String generateUniqueName(String originalName) {
        return UUID.randomUUID() + originalName.substring(originalName.lastIndexOf("."));
    }
    /**
     * 刪除檔案
     */
    public boolean deleteFile(String fileName) {
        String key = prefix + fileName;
        COSClient cosclient = null;
        try {
            //初始化使用者身份資訊(secretId,secretKey)
            COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
            //設定bucket的區域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            // 生成cos客戶端
            cosclient = new COSClient(cosCredentials, clientConfig);
            // 指定要刪除的 bucket 和路徑
            cosclient.deleteObject(bucketName, key);
            // 關閉客戶端(關閉後臺執行緒)
            cosclient.shutdown();
        }catch (CosClientException e) {
            e.printStackTrace();
        }
        return true;
    }
}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import studio.banner.officialwebsite.util.QCloudCosUtils;
/**
 * 騰訊雲物件儲存
 */
@Configuration
public class QCloudCosUtilsConfig {
    @ConfigurationProperties(prefix = "qcloud")
    @Bean
    public QCloudCosUtils qcloudCosUtils() {
        return new QCloudCosUtils();
    }
}
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import studio.banner.officialwebsite.entity.RespBean;
import studio.banner.officialwebsite.service.IFileUploadService;

/**
 * @author 
 * @date 2021/6/6 19:42
 * @role
 */
@RestController
@Api(tags = "騰訊雲上傳介面", value = "TencentPhotoController")
public class TencentPhotoController {
    protected static final Logger logger = LoggerFactory.getLogger(TencentPhotoController.class);
    @Autowired
    private IFileUploadService iFileUploadService;
    @PostMapping(value = "/upload")
    @ApiOperation(value = "騰訊雲上傳介面",notes = "上傳圖片不能為空",httpMethod = "POST")
    public RespBean upload(@RequestPart MultipartFile multipartFile) {
        String url = iFileUploadService.upload(multipartFile);
        return RespBean.ok("上傳成功",url);
    }
    @DeleteMapping("delete")
    @ApiOperation(value = "騰訊雲刪除介面",httpMethod = "DELETE")
    @ApiImplicitParam(name = "fileName",value = "圖片名",dataTypeClass = String.class)
    public RespBean delete(@RequestParam String  fileName) {
        if (iFileUploadService.delete(fileName)){
            return RespBean.ok("刪除成功");
        }
        return RespBean.error("刪除失敗");

    }

}

相關文章