上传图片
官网上找到的是上传绝对路径的代码,其实我们上传时是上传MultipartFile
类型
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,inputStream,null);
这行代码在官网看是两个参数,写的是绝对路径,我们上传时需要给MultipartFile
类型转为InputStream
流类型,我们可以点开PutObjectRequest
会发现,他有重载方法传的是InputStream
流类型,不要被官网骗了
public String uploadImgVuserInfo(MultipartFile file) {String path="https://9uc-1253537498.cos.ap-shanghai.myqcloud.com/";COSCredentials cred = new BasicCOSCredentials("AKIDrpWw6zTz5uXtzKwEn56phJeiaAT3AQCj", "PdldIh2JK6bCXcU7i4F9mAI9mbCXbPHt");// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224// clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));// 3 生成cos客户端COSClient cosClient = new COSClient(cred, clientConfig);// bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式String bucketName = "9uc-1253537498";// 指定要上传到 COS 上对象键// 对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名 `bucket1-1250000000.cos.ap-chengdu.myqcloud.com/mydemo.jpg` 中,对象键为 mydemo.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)String string = new SimpleDateFormat("yyyyMMdd").format(new Date());String key = "/uploads/"+string+"/"+UUID.randomUUID() + ".jpg";//生成唯一图片路径// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口// 大文件上传请参照 API 文档高级 API 上传InputStream inputStream=null;try{inputStream = file.getInputStream();}catch (Exception e){e.printStackTrace();}PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,inputStream,null);PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);String etag = putObjectResult.getETag();System.out.println(etag);// 获取文件的 etagreturn path+key;}
不多逼逼,复制粘贴即可使用…