简体   繁体   中英

sending base64 image to server through ajax

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?

Here is my ajax call :

$.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:

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);
}     

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

 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.

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

Don't do that.

data: {'image': profileImageUrl }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM