尝试通过 AJAX 上传图像但遇到问题...
形式:
{{ Form::open(array('class' => 'update-insertimage-form', "files" => true,)) }}
{{ Form::file('image', array('class' => 'update-insertimage-btn', 'name' => 'update-insertimage-btn')) }}
{{ Form::close() }}
和PHP:
$createImage = Image::make(Input::file('update-insertimage-btn'))->orientate();
$createImage->resize(600, null, function ($constraint) {
$constraint->aspectRatio();
});
$createImage->save("user_uploads/cover_images/TEST.jpeg");
j查询:
$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
$.ajax({
url: rootAsset+'saveUploadedImage',
type: 'post',
cache: false,
dataType: 'json',
data: $('.update-insertimage-form').serialize(),
beforeSend: function() {
},
success: function(data) {
if(data.errors) {
$('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
} else if (data.success) {
$(".form-control-addupdate").append(data.name);
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
我在其他地方使用相同的完全相同的代码,它可以正常工作,但不适用于 AJAX(不确定这是否与它有关(
错误是这样的:
{"error":{"type":"Intervention''Image''Exception''NotReadableException","message":"Image source not readable","file":"'/Applications'/MAMP'/htdocs'/buildsanctuary'/vendor'/intervention'/image'/src'/Intervention'/Image'/AbstractDecoder.php","line":257}}
有什么帮助吗?
您不能序列化图像并将其传递,您需要构造一个 FormData
对象并使用它来发送图像。
var formData = new FormData();
formData.append('update-insertimage-btn[]', $('.update-insertimage-btn')[0].files[0], $('.update-insertimage-btn')[0].files[0].name);
然后,您只需要将其作为数据以及其他一些选项传递给服务器:
data: formData,
processData: false,
contentType: false
现在您可以执行以下操作:
Image::make(Input::file('update-insertimage-btn'))->orientate()
从此处的页面 https://github.com/Intervention/image/blob/master/src/Intervention/Image/AbstractDecoder.php 它正在通过以下检查:
case $this->isDataUrl():
return $this->initFromBinary($this->decodeDataUrl($this->data));
从该函数返回 true:
public function isDataUrl()
{
$data = $this->decodeDataUrl($this->data);
return is_null($data) ? false : true;
}
它正在触发抽象函数initFromBinary
将解码数据URL的结果作为参数传递,并且解码数据URL如下所示:
private function decodeDataUrl($data_url)
{
$pattern = "/^data:(?:image'/[a-zA-Z'-'.]+)(?:charset='".+'")?;base64,(?P<data>.+)$/";
preg_match($pattern, $data_url, $matches);
if (is_array($matches) && array_key_exists('data', $matches)) {
return base64_decode($matches['data']);
}
return null;
}
因此,似乎期望该元素是base64编码的图像,而不是原始的二进制图像;因此,base64在传递图像而不是传递图像时对其进行编码.files[0]