ajax异步上传到springboot简单案例
ajax异步上传springboot简单案例
这个功能其实很简单,在写这个功能的前半个月左右做过这个功能,但是昨天又要重写的时候突然忘记js中FomtData对象的使用,卡了一下,所以记录,以防自己忘记。
var formData = new FormData();
formData.append("multipartFile",$('#shopVideo')[0].files[0]);
formData.append("date",date);
formData.append("password",password);
console.log(formData.get("date"));
$.ajax({ url:"http://localhost:8080/uploadController/index",
dataType:"json",
type:"post",
data:formData,
processData:false,//不作数据处理
contentType: false, // 不设置内容类型
success:function(data){
alert(data.msg);
}
})
其中 date 时间 格式是yyyyMMddHHmmss 用来加密的,而password就是经过date和其他字符加密过的字符串,传给springboot 进行解密。
一下java代码中因为有异步跨域问题,所以加入注解@CrossOrigin(origins = "*")
@Controller @RequestMapping(value="uploadController") public class UploadController { @RequestMapping(value = "upload",method = RequestMethod.POST) @ResponseBody @CrossOrigin(origins = "*") public String index(MultipartFile multipartFile, String date,String password){ ResponseWrapper responseWrapper=new ResponseWrapper(); String newpassword=UtilsMd5.sendMd5(date); System.err.println(newpassword); if(!newpassword.equals(password)){ responseWrapper.setCode(ApiEnum.NOT_POWER.code()); responseWrapper.setMsg(ApiEnum.NOT_POWER.msg()); responseWrapper.setSuccess("success"); return JSON.toJSONString(responseWrapper); } if(StringUtils.isBlank(date)|| StringUtils.isBlank(password)||multipartFile==null || multipartFile.getSize()==0){ responseWrapper.setCode(ApiEnum.ERR.code()); responseWrapper.setMsg(ApiEnum.ERR.msg()); responseWrapper.setSuccess("success"); return JSON.toJSONString(responseWrapper); } //文件原来名称 String multipartFileName=multipartFile.getOriginalFilename(); //文件扩展后缀名称 String extensionName=multipartFileName.substring(multipartFileName.lastIndexOf(".")+1); //创建文件新名称 String newFileName=String.valueOf(System.currentTimeMillis())+"."+extensionName; String basePath="D:/file/"; String yearPath=""; SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); String ymd = sdf.format(new Date()); yearPath =ymd+"/"; String path=basePath+yearPath+newFileName; File fileDir=new File(path); if(!fileDir.exists()){ fileDir.mkdirs(); } try { multipartFile.transferTo(fileDir); responseWrapper.setCode(ApiEnum.SUCCESS.code()); responseWrapper.setMsg(ApiEnum.SUCCESS.msg()); responseWrapper.setSuccess("success"); return JSON.toJSONString(responseWrapper); } catch (IOException e) { e.printStackTrace(); } responseWrapper.setCode(ApiEnum.ERR.code()); responseWrapper.setMsg(ApiEnum.ERR.msg()); responseWrapper.setSuccess("success"); return JSON.toJSONString(responseWrapper); } }

浙公网安备 33010602011771号