通过Ajax向服务器发送Base64图像

4
我已经开发了一个图片裁剪工具,想要将base64格式的图片储存到服务器上。我通过Ajax发送了这个请求。图片以jpg格式储存,但是问题在于它损坏了。请问有什么解决办法吗?
以下是我的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);
}     

当我点击这张图片时,它会显示“我们无法打开此文件”。 - Hola
1
你确定你已经对图像进行了base64编码吗?我没有看到任何暗示表明你已经这样做了。 - RiggsFolly
2
我非常确定您不需要对base64编码的字符串使用encodeURIComponent()。Base64编码应该可以在传输过程中正常工作,无需进行任何操作。这就是它被发明出来的目的。 - RiggsFolly
移除encodeURIComponent后,它显示了“InvalidArgumentException Malformed UTF-8 characters, possibly incorrectly encoded”错误。 - Hola
@Quentin 谢谢你的知识纠正。 - RiggsFolly
显示剩余4条评论
1个回答

3

您没有发送JSON,因此不要声称您正在发送JSON。请将此移除。

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

您正在将一个对象传递给 data

data: {'image': encodeURIComponent(profileImageUrl)}
当你传递一个对象时,jQuery会将其编码为表单URL编码数据。
通过使用encodeURIComponent运行您的代码,您会导致数据被双重编码。
不要这样做。
data: {'image': profileImageUrl }

移除了 encodeURIComponent 后,它显示了 InvalidArgumentException Malformed UTF-8 characters, possibly incorrectly encoded 错误。 - Hola
2
@Hola — 这似乎是图像数据生成的问题。不过,您还没有向我们展示函数的输入,因此很难判断。 - Quentin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接