转换HTML画布内容,在laravel后端向其发送角度形式的数据请求


convert HTML canvas content to send it angular form data request on laravel backend

我的js代码将数据url转换为blob并发送到表单请求是

                 var canv=document.getElementById("mainCanvas");
             // var dataURL = canv.toDataURL();
              var dataURL = canv.toDataURL('image/jpg');
              // .replace("image/png", "image/octet-stream");
              documentData={"image":dataURLtoBlob(dataURL),"gameName":"emperor","userId":'userId',"gameId":56};
              Game.post(documentData).success(function(response){
                console.log(response);
              });

创建blob函数

    function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

我在angular 上的服务工厂

services.factory('Game', ['$http', function($http){
return {
        get:function(){
            return;
        }
    ,   post:function(documentData){
                return $http(               
                { method: 'POST',
                  url: 'public/Game/store',
                  headers:   {   'content-type': 'multipart/form-data'},
                  data: documentData
         });
        }
    ,
        delete:function(){
            return ;
        }
};

}]);

laravel后端

               $image=$request->file('image');

             $image->move("game/".$request->gameName."/play/" ,$request->userId.$request->gameId.".jpg");
             return Response(["success"=>true]);

我反复收到这个错误,说

无法在非对象上调用move

我对将dataurl转换为blob的代码没有信心我试图做的是将dataurl转化为图像文件以形成数据请求

您可以提交到php,只需画布dataURL,然后用file_put_contents()保存,就像这个一样

/*JS - add this code in js in laravel view*/
// take data from canvas
var dataURL = canvas.toDataURL();
/*JS - add this code in js in laravel view*/
// preparing data without any dataURLtoBlob conversion
documentData={"image":dataURL,"gameName":"emperor","userId":'userId',"gameId":56}
/*JS - add this code in js in laravel view*/
// you can also remove headers: {'content-type': 'multipart/form-data'},
// from your Ajax
$http({ 
      method: 'POST',
      url: 'public/Game/store',
      data: documentData
});
/*PHP - laravel backend save form controller*/
//then simply save it as image
file_put_contents( 
     $request->userId.$request->gameId.".jpg",
     base64_decode($request->image) 
);

重要信息:是在保存之前对图像数据调用base64_decode()