功能需求:用戶能夠在評論中上傳圖片,圖片保存到騰訊雲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; }