去購買一個cos java
<dependencies>
<!--因爲寫springcloud項目用到上傳用到,此依賴可忽略-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--核心依賴cos服務-->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
複製代碼
server:
port: 8082
spring:
application:
name: upload-service
servlet:
multipart:
# 限制文件上傳大小
max-file-size: 10MB
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
qcloud:
#初始化用戶身份信息 前往控制檯密鑰管理查看
secretId: ""
secretKey: ""
# 指定要上傳到的存儲桶
bucketName: ""
# 地區選擇
regionName: ""
複製代碼
/** * @Author :cjy * @description :cos配置屬性類 使用ConfigurationProperties註解可將配置文件(yml/properties)中指定前綴的配置轉爲bean * @CreateTime :Created in 2019/9/8 23:39 */
@Data
@ConfigurationProperties(prefix = "qcloud")
public class COSProperties {
// 初始化用戶身份信息 前往密鑰管理查看
private String secretId;
// 初始化用戶身份信息 前往密鑰管理查看
private String secretKey;
// 指定要上傳到的存儲桶
private String bucketName;
//指定要上傳的地區名稱 去控制檯查詢
private String regionName;
}
複製代碼
/** * @Author :cjy * @description :COSClient 是調用 COS API 接口的對象 * @CreateTime :Created in 2019/9/8 23:16 */
@Configuration
@EnableConfigurationProperties(COSProperties.class)
public class COSClientConfig {
@Autowired
private COSProperties cosProperties;
@Bean
public COSClient cosClient(){
// 1 初始化用戶身份信息(secretId, secretKey)。
// String secretId = "AKIDcKlIXWKgy3vc4Jj9tNblgW8UaPJxpZj8";
// String secretKey = "MUPecJmyuZzVs36vU8VeWLuCC5hPHxSS";
COSCredentials cred = new BasicCOSCredentials(cosProperties.getSecretId(),cosProperties.getSecretKey());
// 2 設置 bucket 的區域, COS 地域的簡稱請參照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了設置 region, https(默認 http), 超時, 代理等 set 方法, 使用可參見源碼或者常見問題 Java SDK 部分。
Region region = new Region(cosProperties.getRegionName());
ClientConfig clientConfig = new ClientConfig(region);
// 3 生成 cos 客戶端。
COSClient cosClient = new COSClient(cred, clientConfig);
return cosClient;
}
}
複製代碼
/** * @Author :cjy * @description : * @CreateTime :Created in 2019/9/7 16:09 */
@Service
@Slf4j
public class UploadService {
String key;
@Autowired
private COSClient cosClient;
@Autowired
private COSProperties cosProperties;
// 支持的文件類型
private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");
public String uploadImage(MultipartFile file) {
try {
// 一、圖片信息校驗
// 1)校驗文件類型
String type = file.getContentType(); //獲取文件格式
if (!suffixes.contains(type)) {
// logger.info("上傳失敗,文件類型不匹配:{}", type);
return null;
}
// 2)校驗圖片內容
BufferedImage image = ImageIO.read(file.getInputStream());
if (image == null) {
// logger.info("上傳失敗,文件內容不符合要求");
return null;
}
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType(type);
UUID uuid = UUID.randomUUID();
// 指定要上傳到 COS 上對象鍵 此key是文件惟一標識
key = uuid.toString().replace("-","")+".jpg";
PutObjectRequest putObjectRequest = new PutObjectRequest(cosProperties.getBucketName(), key, file.getInputStream(),objectMetadata);
//使用cosClient調用第三方接口
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
log.info(putObjectRequest+"");
//返回路徑
}catch (Exception e){
e.printStackTrace();
}
//拼接返回路徑
String imagePath = "https://" + cosProperties.getBucketName() + ".cos." + cosProperties.getRegionName() + ".myqcloud.com/" + key;
return imagePath;
}
}
複製代碼
@RestController
@RequestMapping("upload")
@Slf4j
public class UploadController {
@Autowired
private UploadService uploadService;
/** * 上傳圖片 * @param file * @return */
@PostMapping("image")
public ResponseEntity<String> uploadImage(@RequestParam("file")MultipartFile file){
String url=uploadService.uploadImage(file);
log.info("返回地址:【{}】",url);
return ResponseEntity.ok(url);
}
}
複製代碼
postman測試成功web
官方sdk文檔: cloud.tencent.com/document/pr…