【问题标题】:Upload Image In Laravel With jQuery AJAX使用 jQuery AJAX 在 Laravel 中上传图片
【发布时间】:2021-07-14 10:05:27
【问题描述】:

我正在尝试使用 jQuery AJAX 在 Laravel 中上传照片。但它总是失败很多次并显示错误消息

照片必须是图片。 照片必须是以下类型的文件:jpeg、png、jpg、gif、SVG。

我不知道为什么。我下面的代码有什么问题?

控制器

$validator = \Validator::make($request->all(), [
    'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
    
if ($files = $request->file('image')) {
    //---Insert new file
    $destinationPath = 'public/product_images/'; // upload path
    $image_path = date('YmdHis') . "." . $files->getClientOriginalExtension();
    $files->move($destinationPath, $image_path);
}

$productId = DB::table('products')->insertGetId([
    'product_photo' => $image_path
]);

查看

$("#photo").fileinput({
    theme: 'fa',
    uploadUrl: '{{ route('products.store') }}',
    uploadExtraData: function() {
        return {
            _token: $("input[name='_token']").val(),
        };
    },
    allowedFileExtensions: ['jpg', 'png', 'gif'],
    overwriteInitial: false,
    maxFileSize: 2000,
    maxFilesNum: 5,
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});
                        
$('#saveBtnForCreate').click(function(e) {
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        url: "{{ route('products.store') }}",
        method: 'post',
        enctype: 'multipart/form-data',
        cache: false,
        dataType: 'JSON',
        data: {
            photo: $('#photo').val()
        },
        success: function(result) {
            if (result.errors) {
                $('.alert-danger').html('An error in your input!');
                $.each(result.errors, function(key, value) {
                    $('.alert-danger').show();
                    $('.alert-danger').append('<strong><li>' + value + '</li></strong>');
                });
            } 
        }
    });
});

【问题讨论】:

    标签: jquery ajax laravel laravel-5


    【解决方案1】:

    您上传的文件显然不符合验证规则。您在代码中遇到的另一个问题是在传递photo 时尝试保存image 的行。以下代码来自laravel doc for storing files

    $validator = \Validator::make($request->all(), [
        'photo' => 'required|file|mimes:jpeg,png,jpg,gif,svg',
    ]);
    if ($files = $request->file('photo')) {
        //insert new file
        $destinationPath = 'public/product_images/'; // upload path
        $image_path = $request->file('photo')->store($destinationPath);
    }
    

    【讨论】:

    • formData 怎么样?
    • @SeadLab for jquery 部分参考this
    • 我不知道在这种情况下如何实现formData。可以给我写一个更具体的代码吗?
    猜你喜欢
    • 2017-11-04
    • 2020-01-11
    • 2020-07-04
    • 2020-01-26
    • 2021-09-05
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    相关资源
    最近更新 更多