Springboot:華為雲obs檔案上傳和刪除
阿新 • • 發佈:2021-01-31
不講別的,直接看程式碼
準備
AccessKey:訪問金鑰
SecretKey:訪問金鑰
endPoint:終端節點
bucketName:桶
1 新增maven依賴
<dependency> <groupId>com.huaweicloud</groupId> <artifactId>esdk-obs-java</artifactId> <version>3.19.7</version> </dependency>
2 新增obs的配置資訊
# huawei ods
huawei.obs.ak=hajkfhdsajkhjdkahsfjs
huawei.obs.sk=hjaksjfhdakdfhajkfhdsajkhjdkahsfjsadhaljkhdfsd
# 上傳的endPoint
huawei.obs.upload.endPoint=endPoint.com
# 訪問的endPoint
huawei.obs.access.endPoint=https://endPoint.com
# 桶
huawei.obs.bucketName=obs-bucket-dev
3 配置obs
import com.obs.services.ObsClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ObsConfig { @Value("${huawei.obs.ak}") private String ak; @Value("${huawei.obs.sk}") private String sk; @Value("${huawei.obs.upload.endPoint}") private String endPoint; @Bean public ObsClient getObsClient(){ ObsClient obsClient = new ObsClient(ak, sk, endPoint); return obsClient; } }
4 建立obs工具類,提供上傳和刪除功能
import com.obs.services.ObsClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; @Component public class ObsUtil { @Autowired private ObsClient obsClient; @Value("${huawei.obs.bucketName}") private String bucketName; //上傳檔案,multipartFile就是你要的檔案, //objectKey就是檔名,如果桶中有資料夾的話,如往test檔案上傳test.txt檔案,那麼objectKey就是test/test.txt public void uploadFile(MultipartFile multipartFile, String objectKey) throws Exception{ InputStream inputStream = multipartFile.getInputStream(); obsClient.putObject(bucketName, objectKey, inputStream); inputStream.close(); obsClient.close(); } public void deleteFile(String objectKey) throws Exception{ obsClient.deleteObject(bucketName, objectKey); obsClient.close(); } }