如果是表單普通方式提交,後台驗證沒什麼問題:
$file = $request->avatar;
$input = array('image' => $file);
$rules = array(
'image' => 'image'
);
$validator = \Validator::make($input, $rules);
if ( $validator->fails() ) {
return \Response::json([
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
]);
}
可是,用formData物件提交,這個圖片文件轉換成了blob文件,就不能驗證了:
$('#uploadAvatar').on('click', function (e) {
$('#uploadAvatar').html('正在保存...');
$("#image").cropper('getCroppedCanvas').toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "{{ url('/avatar') }}",
processData: false,
contentType: false,
cache: false,
data: formData
}).done(function (response) {
showResponse(response);
}).fail(function (data) {
alert('提交失败,请尝试重新提交');
});
});
});
後台怎麼才可以驗證blob檔案是圖片?
过去多啦不再A梦2017-05-16 16:51:55
很簡單啊,搞個臨時變數還原回來不就好了?$file = file_put_contents('/path/to/new/file_name', $blob);