【问题标题】:Adding an image to an upload in ajax将图像添加到 ajax 中的上传
【发布时间】:2019-03-15 23:13:36
【问题描述】:

我创建了一个表单,通过单击按钮将数据上传到使用 Ajax 的数据库。我尝试将图像(文件)上传添加到表单,但它似乎在表单上生成错误并破坏正在工作的表单 - 表单在按钮单击时不执行任何操作(控制台中没有显示任何内容它的工作不起作用)。

谁能看出我哪里出错了?

PHP:

$product = Product::find($products_id); 
$comment = new Comment(); 
$comment->title = $request['title']; 
$comment->comment = $request['comment']; 
$comment->products()->associate($product);
 $comment->user_id = $request['userid']; 
$comment->save();

    if ($request->hasFile('image')) {
    $picture = new Picture();
    $image = $request->file('image');
    $filename = uniqid('img_') . '.' . $image->getClientOriginalExtension();
    $location = public_path('images/' . $filename);
    Image::make($image)->save($location);
    $picture->image = $filename;
 $picture->products()->associate($product);
    $picture->user_id = $request->user()->id;
    $picture->comments()->associate($comment);
    $picture->save();

}

HTML

{!! Form::open((['route' => ['comments.store', $product->id], 'method' => 'POST', 'files' => 'true'])) !!}
 <div class="comment-form">
 {{ Form::label('title', 'Title (Give a short summary)') }}
 {{Form::text('title', null, ['class'=>'form-control title', 'minlength'=>'2','maxlength'=>'30'])}}
  {{Form::label('comment', 'Add comment (2000 character limit)')}}
   {{Form::textarea('comment', null, ['class'=>'form-control review'])}}
   {!!Form::hidden('user_id', Auth::user()->id, array('class' => 'userid'))  !!}
   {{Form::label('image', 'Upload image')}}
   {{ Form::file('image', null, array('class' => 'image1')}}

      {{ Form::submit('Add Review', ['class' => 'btn btn-send btn-block send-review'])}}
      {!! Form::close() !!}
 </div>

JS AJAX:

    $('.send-review').on('click', function(dl) {

        var title = $('.title').val();
        var rating = $('.rating').val();
        var comment = $('.review').val();
        var userid = $('.userid').val();
        var image = $('.image1').prop('files')[0];
        var form_data = new FormData();
        form_data.append('title', title);
        form_data.append('review', comment);
        form_data.append('userid', userid);
        form_data.append('image', image);
        dl.preventDefault();
        $.ajax({
            method: 'POST',
            url: urlCreateReview,
            data: form_data,
            processData: false,
            contentType: false
        })
                .done(function() {

        });

    });

【问题讨论】:

    标签: javascript ajax laravel laravel-5


    【解决方案1】:

    您正在选择带有$('.image1') 的文件元素,但您将其类设置为'class' =&gt; 'image',因此您应该选择它

    var image = $('.image').prop('files')[0];
    

    【讨论】:

    • 是的,我在发布后不久就修复了这个问题,但仍然得到相同的表单无法正常工作的结果。你还能看到其他错误吗?
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2018-06-14
    • 2013-01-01
    • 2019-03-15
    • 2020-08-18
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多