首页 > 代码库 > ajax java base64 图片储存

ajax java base64 图片储存

js代码
//利用formdata上传
 1 var dataUrl = $(‘#canvas‘).getDataUrl(); 2 var img = $(‘<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="http://www.mamicode.com/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       Iterator<String> fileNames = 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<imgByte.length;++i)18       {19          if(imgByte[i]<0)20          {//调整异常数据21              imgByte[i]+=256;22          }23       }24       //生成jpeg图片25       String imgFilePath = "d://222.jpg";//新生成的图片26       OutputStream out = new FileOutputStream(imgFilePath);27       out.write(imgByte);28       out.flush();29       out.close();30     }

 

ajax java base64 图片储存