Laravel AJAX图像上传验证

时间:2016-03-29 04:01:13

标签: ajax laravel laravel-5.2

我在此AJAX POST上验证文件上传时遇到问题。这是我到目前为止所拥有的。需要'验证不断回来告诉我选择一个图像。当我使用图像调度js变量console.log()时,它会正确显示文件路径。

查看:

<form role="form" method="post" action="{{ route('profile.edit') }}" enctype="multipart/form-data">
    <div class="form-group new-pic{{ $errors->has('profile-image') ? ' has-error' : '' }}">
        <input type="file" id="newProfilePic" name="profile-image"/>        
    </div>
</form>

JS:

$('.btn-edit-profile-pic').click(function(e){
    e.preventDefault();

    var newPic = $('#newProfilePic').val();

    $.ajax({
        type: "POST",
        url: "/profile-edit",
        data: newPic,
        error: function(data) {
            var errors = $.parseJSON(data.responseText);
            console.log(errors);
        },
        success: function() {

        }    
    });  
});

控制器:

if ($request->ajax())
{
    $this->validate($request, [
        'newPic' => 'required|image|max:4999'
    ],[
        'required' => 'You must select an image',
        'image' => 'The file must be an image',
        'max' => 'The image file size must be less than 5mb'
    ]);

    $extension = Input::file('profile-image')->getClientOriginalExtension();
    $fileName = rand(11111,99999).'.'.$extension;

    $image = Image::make(Input::file('profile-image'))
        ->orientate()
        ->resize(300, null, function ($constraint) { 
            $constraint->aspectRatio();
        })
        ->save('images/profiles/'.$fileName);

    Auth::user()->update([
        'image_path' => $fileName,
    ]);
}

1 个答案:

答案 0 :(得分:-1)

这是一种预期的行为,您无法通过XMLHTTPRequest发送上传文件,这就是为什么您将始终收到图像文件所需的验证。

您可以使用ajaxfileuploader插件(他们在iframe中创建一个新表单并提交)

[http://www.sitepoint.com/10-jquery-ajax-file-uploader-plugins/]