问题:
解决办法 :
给metadata的contentlength属性赋值所要传输文件字节流的字节数.
objectmetadata metadata = new objectmetadata(); metadata.setcontentlength(bytearrayinputstream.available());
另外cos上传文件的工具类分享给大家.
@component
@configurationproperties(prefix = "tencent")
@data
public class tencentcosproperties {
private string endpoint;
private string accesskeyid;
private string accesskeysecret;
private string bucketname;
}
=======================================================
@configuration
@slf4j
public class cosconfiguration {
@bean
@conditionalonmissingbean
public tencentcosutil tencentcosutil(tencentcosproperties tencentcosproperties){
return new tencentcosutil(
tencentcosproperties.getendpoint(),
tencentcosproperties.getaccesskeyid(),
tencentcosproperties.getaccesskeysecret(),
tencentcosproperties.getbucketname());
}
}
=======================================================
@data
@allargsconstructor
@slf4j
public class tencentcosutil {
private string endpoint;
private string accesskeyid;
private string accesskeysecret;
private string bucketname;
/**
* 文件上传
*
* @param bytes 文件byte数组
* @param objectname 文件名称
* @return
*/
public string upload(byte[] bytes, string objectname) {
// 创建ossclient实例。
coscredentials cred = new basiccoscredentials(accesskeyid, accesskeysecret);
region region = new region(com.tencentcloudapi.common.profile.region.guangzhou.tostring());
clientconfig clientconfig = new clientconfig(region);
clientconfig.sethttpprotocol(httpprotocol.https);
cosclient cosclient = new cosclient(cred, clientconfig);
string folder = "images/";
string key = folder + objectname;
objectmetadata metadata = new objectmetadata();
metadata.setcontenttype("image/png");
bytearrayinputstream bytearrayinputstream = new bytearrayinputstream(bytes);
metadata.setcontentlength(bytearrayinputstream.available());
putobjectrequest putobjectrequest = new putobjectrequest(bucketname, key, bytearrayinputstream, metadata);
putobjectresult putobjectresult = cosclient.putobject(putobjectrequest);
//文件访问路径规则 https://bucketname.endpoint/objectname
stringbuilder stringbuilder = new stringbuilder("");
stringbuilder
.append(endpoint)
.append("/")
.append(key);
log.info("文件上传到:{}", stringbuilder.tostring());
cosclient.shutdown();
return stringbuilder.tostring();
}
}
发表评论