js代码
//利用formdata上传
1 var dataUrl = $('#canvas').getDataUrl(); 2 var img = $('').attr('src', dataUrl); //显示图片 3 var oMyForm = new FormData(); //创建formdata 4 var blobBin = dataURLtoBlob(dataUrl); //base64转换blob 5 oMyForm.append("blobObject", blobBin); //想formData添加blob数据 6 $.ajax({ 7 url: $.getUrl()+"activity/updateImg", 8 type: "POST", 9 data: oMyForm,10 async: false,11 cache: false,12 contentType: false,13 processData: false,14 success: function (msg) {15 console.log("yes");16 }17 });18 19 //**dataURL to blob** dataURL转换blob20 function dataURLtoBlob(dataurl) {21 var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],22 bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);23 while (n--) {24 u8arr[n] = bstr.charCodeAt(n);25 }26 return new Blob([u8arr], { type: mime });27 }
java代码
//spring mvc
1 @RequestMapping(value="updateImg",method=RequestMethod.POST) 2 public void upLoad(HttpServletRequest request,HttpServletResponse response) throws IOException { 3 System.out.println("enter..."); 4 // 从请求中获取到文件信息需要将请求转换为MultipartHttpServletRequest类型 5 MultipartHttpServletRequest MulRequest = request instanceof MultipartHttpServletRequest ? (MultipartHttpServletRequest) request : null; 6 IteratorfileNames = MulRequest.getFileNames(); 7 byte[] imgByte = null; 8 if (fileNames.hasNext()) { // 遍历请求中的图片信息 9 String fileName = fileNames.next(); // 图片对应的参数名10 MultipartFile file = MulRequest.getFile(fileName); // 获取到图片11 if (file != null) {12 System.out.println("file.getSize():" + file.getSize()); // 图片大小13 imgByte=file.getBytes();// 可以获取到图片的字节数组14 }15 }16 17 for(int i=0;i