今天给前端做一个功能,着实费了一番功夫。
前提:前端说让我写个方法,在ueditor中配置接口路径后,ueditor会自动调用接口,要实现单图、多图、视频等上传。
第一个坑:从ueditor过来的请求,参数不在requestBody中,而是在paramter中。所以对应的参数要去request中取。
第二个坑:不知道流怎么从request中获取,找了一些大牛的博客,找到了解决方法。
第三个坑:原来不知道七牛提供了一个可以直接将外网图片url直接存到七牛服务器上,并返回七牛上的url。
好了,话不多说,上代码!
@RequestMapping("/uploadAction") @ResponseBody public String uploadAction(HttpServletRequest request)throws Exception { String action = request.getParameter("action"); MultipartFile upfile = null; if(action.equals("uploadimage") || action.equals("uploadvideo")){ //如果是在request中传流,就要转换成这种request,才能取到文件 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; upfile = multipartRequest.getFile("upfile"); } System.out.println("uploadAction------->action:"+action); JSONObject json = new JSONObject(); String uuid = UUID.randomUUID().toString(); QiniuUploadResultVo qiniuUploadResultVo = null; try{ request.setCharacterEncoding("UTF-8"); switch (action){ case"config": String rootPath = this.getClass().getResource("/").getPath(); File jsonFile = ResourceUtils.getFile(rootPath+"config.json"); String configJson = FileUtils.readFileToString(jsonFile,"UTF-8"); return configJson; case"uploadimage": qiniuUploadResultVo = qiNiuService.upload(upfile.getInputStream(),"weiyou/"+uuid); qiniuUploadResultVo.setKey("weiyou/"+uuid); json.put("data",qiniuUploadResultVo); return json.toJSONString(); case"uploadvideo": qiniuUploadResultVo = qiNiuService.upload(upfile.getInputStream(),"weiyou/"+uuid); qiniuUploadResultVo.setKey("weiyou/"+uuid); json.put("data",qiniuUploadResultVo); return json.toJSONString(); case"catchimage": //处理多张外网图片上传七牛逻辑 //下面这行代码注意,ueditor很坑,它请求的数组的key是source[],而不是source!!!! String[] source = request.getParameterValues("source[]"); List<String> list = Arrays.asList(source); //这个方法就是下面的 List<JSONObject> result = qiNiuService.fetch(list); return JSONObject.toJSONString(result).toString(); } }catch (Exception e){ e.printStackTrace(); } return ""; }
public List<JSONObject> fetch(List<String> list){ Auth auth = Auth.create(accessKey, secretKey); BucketManager bucketManager = new BucketManager(auth); List<JSONObject> result = new ArrayList<>(); try{ if(list != null && list.size() > 0){ for(int i = 0;i<list.size();i++){ String uuid = UUID.randomUUID().toString(); DefaultPutRet putret = bucketManager.fetch(list.get(i), bucket, uuid); String url = baseUrl +"/" + uuid; String source = "source["+i+"]"; String state = "SUCCESS"; JSONObject jsonObject = new JSONObject(); jsonObject.put("url",url); jsonObject.put("source",source); jsonObject.put("state",state); result.add(jsonObject); } } }catch (QiniuException ex) { System.err.println(ex.response.toString()); } return result; }
还有问题的,给我留言!