JAVA上传base64图片至腾讯云COS
腾讯云COS java sdk 上传图片示例
引入pom
引入java sdk的pom
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.4.5</version>
</dependency>
注意事项
引入后如果有 NoClassDefFoundError 异常,则检查项目引入和Apache http组件版本号是否和 cos_api 内部引用的一致,以及引入顺序。我的如下:
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.4.5</version>
</dependency>
<!-- http请求 s -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<!-- http请求 e-->
处理图片
处理图片base64字符串
图片base64字符串默认有 data:image/{xxx};base64, (xxx为图片格式) 这样的字符开头,如果直接带着转为图片是打不开的,需要处理。处理方法如下:
public class ImgUtil {
private static String IMG_TYPE = "jpg,png,jpeg";
/**
* @param imgString 图片base64
* @return java.lang.String
* @author cuishilei
* @date 2018/9/21
*/
public static String checkBase64Type(String imgString) {
String[] imgTypes = IMG_TYPE.split(",");
String regex;
for (String v : imgTypes) {
regex = MessageFormat.format("data:image/{0};base64,", v);
if (imgString.contains(regex)) {
return v;
}
}
return null;
}
/**
* @param imgString 图片base64
* @return java.lang.String
* @author cuishilei
* @date 2018/9/21
*/
public static String replaceBase64Pre(String imgString) {
String[] imgTypes = IMG_TYPE.split(",");
Pattern pattern;
Matcher matcher;
String regex;
for (String v : imgTypes) {
regex = MessageFormat.format("data:image/{0};base64,", v);
if (imgString.contains(regex)) {
return imgString.replaceAll(regex, "");
}
}
return imgString;
}
}
base64 转 inputstream 注意事项
通过网络 post 传到 web 后台的base64串中的 + 号会变为空格,需要处理
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = decoder.decodeBuffer(imgData);
//调整异常数据
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
调用 sdk 上传图片
接入 sdk 的 spring 组件代码如下:
@Slf4j
@Component
public class QcloudXmlApi {
@Value("${qcloud.appId}")
private String appId;
@Value("${qcloud.secretId}")
private String secretId;
@Value("${qcloud.secretKey}")
private String secretKey;
@Value("${qcloud.bucketName}")
private String bucketName;
@Value("${qcloud.region}")
private String region;
@Value("${qcloud.path}")
private String path;
@Value("${qcloud.baseUrl}")
private String baseUrl;
private COSClient cosclient;
@PostConstruct
public void init() {
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置bucket的区域
ClientConfig clientConfig = new ClientConfig(new Region(region));
// 3 生成cos客户端
cosclient = new COSClient(cred, clientConfig);
}
/**
* 上传图片
*
* @param inputStream 输入流
* @param uploadFileName 远程文件名,不必带后缀
* @param suffix 文件后缀
* @return com.reward.bean.ResultInfo<java.lang.String>
* @author cuishilei
* @date 2018/9/21
*/
public ResultInfo<String> uploadImg(InputStream inputStream, String uploadFileName, String suffix) {
ResultInfo<String> resultInfo = new ResultInfo<>();
try {
String filePath = path + uploadFileName + "." + suffix;
ObjectMetadata objectMetadata = new ObjectMetadata();
// 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据,存在内存OOM的情况
objectMetadata.setContentLength(inputStream.available());
// 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
objectMetadata.setContentType("image/" + suffix);
PutObjectRequest putObjectRequest =
new PutObjectRequest(bucketName + "-" + appId, filePath, inputStream, objectMetadata);
// 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
putObjectRequest.setStorageClass(StorageClass.Standard);
PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
resultInfo.setData(baseUrl + filePath);
} catch (Exception e) {
resultInfo.fail(e.getMessage());
log.error("error", e);
} finally {
// 关闭客户端
cosclient.shutdown();
}
return resultInfo;
}
}
使用 demo
@RequestMapping(value = "/uploadBase64", produces = "application/json;charset=UTF-8")
@ResponseBody
public ResultInfo uploadBase64(@RequestParam(value = "imgData") String imgData) {
ResultInfo resultInfo = new ResultInfo();
try {
//检查文件格式
String checkType = ImgUtil.checkBase64Type(imgData);
if (checkType == null) {
resultInfo.fail("不支持的图片格式!");
}
//处理 base64 前缀
imgData = ImgUtil.replaceBase64Pre(imgData);
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = decoder.decodeBuffer(imgData);
//调整异常数据
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
InputStream stream = new ByteArrayInputStream(bytes);
//上传
resultInfo = qcloudXmlApi.uploadImg(stream, "lalala", checkType);
} catch (Exception e) {
log.error("上传图片失败", e);
resultInfo.fail("上传图片失败,请稍候再试!");
}
return resultInfo;
}
结束。
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 rockeycui@163.com
文章标题:JAVA上传base64图片至腾讯云COS
文章字数:940
本文作者:崔石磊(RockeyCui)
发布时间:2018-10-03, 19:24:36
原始链接:https://cuishilei.com/JAVA上传base64图片至腾讯云COS.html版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。