H5实现图片预览、裁剪、批量上传

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

前端代码: 




  
  
  
  
  
  
  Cropper Test
  
  


    

服务端代码:结合Spring MVC实现上传,关于spring mvc上传网上很多,配置就不详细说明了

@RestController
public class MainController {
    private static SimpleDateFormat df = new SimpleDateFormat("YYYY/MM/dd/");

    private String uploadUrlPrefix = "http://localhost/upload";
    private String uploadDir = "/data/upload";
    
    @RequestMapping(value = "/multiUpload", name = "批量上传图片")
    public String uploadMulti(@RequestParam("file") CommonsMultipartFile[] files) throws IOException {
        JSONObject json = new JSONObject();
        if(files == null) {
            json.put("code", -1);
            json.put("message", "没有上传文件");
            return json.toJSONString();
        }
        JSONArray jsonArray = new JSONArray();
        json.put("data", jsonArray);
        String uuid = UUID.randomUUID().toString();
        for(CommonsMultipartFile file : files) {
            String oriFileName = file.getOriginalFilename();
            StringBuilder newFileName = new StringBuilder();
            boolean isBase = false;
            if(oriFileName.matches(".*_\\d+x\\d+\\.\\w+")) {
                newFileName.append(oriFileName.replaceFirst("(.*)(_\\d+x\\d+\\.\\w+)", uuid+"$2"));
            } else {
                newFileName.append(uuid).append(oriFileName.substring(oriFileName.lastIndexOf('.')));
                isBase = true;
            }
            String timeDir = df.format(new Date());
            String imgPath = uploadDir + File.separatorChar + timeDir + fileName;
            log.info("save file name: {}", newFileName);
            
            File imgFile = new File(imgPath);
            if(!imgFile.getParentFile().exists()) {
                imgFile.getParentFile().mkdirs();
            }
            //保存文件
            file.transferTo(imgFile);
            JSONObject imgJson = new JSONObject();
            imgJson.put("oriFileName", oriFileName);
            imgJson.put("state", "SUCCESS");
            imgJson.put("url", uploadUrlPrefix + "/" + uri);
            jsonArray.add(imgJson);
            if(isBase) {
                json.put("baseUrl", imgJson.getString("url"));
            }
        }
        json.put("code", 0);
        json.put("message", "上传成功");
        return json.toJSONString();
    }
}

cropper js 参考:https://fengyuanchen.github.io/cropper/

async异步库参考:https://github.com/caolan/async

大体思路:

  1.  用cropper js 实现图片预览,裁剪
  2.  调用cropper js的getCroppedCanvas来获取不同尺寸的图片canvas
  3.  结合async 实现顺序地从canvas.toBlob的回调中获取到blob,很好的解决了异步的问题,这点非常重要
  4. 用FormData装载图片,ajax上传

效果:

H5实现图片预览、裁剪、批量上传_第1张图片

H5实现图片预览、裁剪、批量上传_第2张图片

 

 

 

转载于:https://my.oschina.net/u/565351/blog/692777

你可能感兴趣的:(H5实现图片预览、裁剪、批量上传)