在ajax中将图像添加到上传中

时间:2018-10-11 00:21:12

标签: javascript ajax laravel laravel-5

我创建了一个表单,通过单击按钮,我可以使用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() {

        });

    });

1 个答案:

答案 0 :(得分:0)

您正在使用$('.image1')选择文件元素,但是将其类别设置为'class' => 'image',因此应将其选择为

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