通过ajax将base64映像发送到服务器

时间:2022-11-04 20:37:23

I have build a image cropper tool from there i wanted to store that base64 image to server. I have sent it through Ajax. Image got stored in jpg format.But the problem is it's got corrupted. Can anyone suggest me what could be the solution?

我已经构建了一个图像裁剪工具,我想将base64图像存储到服务器。我通过Ajax发送了它。图像以jpg格式存储。但问题是它已损坏。任何人都可以建议我可能是什么解决方案?

Here is my ajax call :

这是我的ajax电话:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$.ajax({
    method: 'post',
    url: 'updateProfilePicture',
    cache: false,
    contentType: "application/json; charset=utf-8",
    data: {'image': encodeURIComponent(profileImageUrl)},
    success: function (data) {
        alert(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {

    }
});

Here is the controller for converting base64 to normal image and stored to server:

这是用于将base64转换为普通图像并存储到服务器的控制器:

public function updateProfile(Request $request)
{
    $base64img = str_replace('data:image/jpeg;base64,', '', $request->Input(['image']));
    $data = base64_decode($base64img);
    $file = public_path() . '/users/' .'123123123.jpg';
    file_put_contents($file, $data);
    return \Response::json($data);
}     

1 个解决方案

#1


2  

You aren't sending JSON so don't claim you are sending JSON. Remove this.

您没有发送JSON,所以不要声称您正在发送JSON。删除它。

contentType: "application/json; charset=utf-8",

You are passing an object to data:

您正在将对象传递给数据:

data: {'image': encodeURIComponent(profileImageUrl)}

When you pass an object, jQuery will encode it as form URL encoded data.

传递对象时,jQuery会将其编码为表单URL编码数据。

By running your code through encodeURIComponent you cause the data to be double encoded.

通过encodeURIComponent运行代码,可以使数据进行双重编码。

Don't do that.

不要那样做。

data: {'image': profileImageUrl }

#1


2  

You aren't sending JSON so don't claim you are sending JSON. Remove this.

您没有发送JSON,所以不要声称您正在发送JSON。删除它。

contentType: "application/json; charset=utf-8",

You are passing an object to data:

您正在将对象传递给数据:

data: {'image': encodeURIComponent(profileImageUrl)}

When you pass an object, jQuery will encode it as form URL encoded data.

传递对象时,jQuery会将其编码为表单URL编码数据。

By running your code through encodeURIComponent you cause the data to be double encoded.

通过encodeURIComponent运行代码,可以使数据进行双重编码。

Don't do that.

不要那样做。

data: {'image': profileImageUrl }