2019独角兽企业重金招聘Python工程师标准>>>
前端代码:
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
大体思路:
- 用cropper js 实现图片预览,裁剪
- 调用cropper js的getCroppedCanvas来获取不同尺寸的图片canvas
- 结合async 实现顺序地从canvas.toBlob的回调中获取到blob,很好的解决了异步的问题,这点非常重要
- 用FormData装载图片,ajax上传
效果: