微信小程序上传图片到COS腾讯云
Posted 奇迹再现
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信小程序上传图片到COS腾讯云相关的知识,希望对你有一定的参考价值。
功能需求:用户可以在评论中上传图片,图片保存到腾讯云COS上。
实现方法,微信小程序需要往后台传一个代表文件的参数file代表文件,借助MultipartFile获得文件的路径和文件名等信息。
关键实现代码:
@RequestMapping(value = "/plugins/fileServer/fileservice/sales/admin", method = RequestMethod.POST)
void postAdmin(@RequestParam(value = "file", required = false) MultipartFile file, Integer preview_height, Integer preview_width, String target, String type, HttpServletRequest request, HttpServletResponse response) {
String body = "";
if (file == null) {
response.setStatus(401);
body = GsonUtils.obj2Gson(OutAdmin.error(401, "no file upload")).toString();
ResponseUtils.renderJson(response, body);
return;
}
if (preview_width == null) {
preview_width = 128;
}
if (preview_height == null) {
preview_height = 128;
}
String uploadPath = "/default";
if (!StringUtils.isBlank(target)) {
uploadPath = "/" + target;
}
String uploadPreviewPath = uploadPath + "/preview";
CmsSite site = CmsUtils.getSite(request);
String fileUrl = upload(site, file, uploadPath);
if (fileUrl == null) {
response.setStatus(401);
body = GsonUtils.obj2Gson(OutAdmin.error(401, "upload error")).toString();
ResponseUtils.renderJson(response, body);
return;
}
String preview_fileUrl = uploadPreview(site, file, uploadPreviewPath, preview_width, preview_height);
if (preview_fileUrl == null) {
response.setStatus(401);
body = GsonUtils.obj2Gson(OutAdmin.error(401, "upload preview error")).toString();
ResponseUtils.renderJson(response, body);
return;
}
String content_type = file.getContentType();
String download_link = fileUrl;
String fileid = FilenameUtils.getBaseName(fileUrl);
String filename = FilenameUtils.getName(fileUrl);
String preview_link = preview_fileUrl;
Integer result = 0;
OutAdmin outAdmin = new OutAdmin(content_type, download_link, fileid, filename, preview_link, result);
body = GsonUtils.obj2Gson(outAdmin).toString();
ResponseUtils.renderJson(response, body);
}
private String upload(CmsSite site, MultipartFile file, String uploadPath) {
String origName = file.getOriginalFilename();
Long fileSize = file.getSize() / 1024;//单位KB
String ext = FilenameUtils.getExtension(origName).toLowerCase(Locale.ENGLISH);
String fileUrl = null;
try {
if (site.getUploadOss() != null) {
// 支持上传(腾讯)云
CmsOss oss = site.getUploadOss();
fileUrl = oss.storeByExt(uploadPath, ext, file.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
return fileUrl;
}
以上是关于微信小程序上传图片到COS腾讯云的主要内容,如果未能解决你的问题,请参考以下文章