我已经开发了一个图片裁剪工具,想要将base64格式的图片储存到服务器上。我通过Ajax发送了这个请求。图片以jpg格式储存,但是问题在于它损坏了。请问有什么解决办法吗?
以下是我的ajax调用代码:
以下是我的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) {
}
});
这是用于将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);
}
encodeURIComponent()
。Base64编码应该可以在传输过程中正常工作,无需进行任何操作。这就是它被发明出来的目的。 - RiggsFolly