首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在ajax中将图像添加到上传

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

Stack Overflow用户
提问于 2018-10-11 08:21:12
回答 1查看 36关注 0票数 0

我已经创建了一个表单,只需单击一下按钮,就可以使用Ajax将数据上传到数据库。我试图添加一个图片(文件)上传到表单中,但它似乎在表单上生成了一个错误,并破坏了正常工作的表单--表单在单击按钮时什么也不做(控制台中没有显示任何内容表明其工作正常)。

有人能看出我哪里错了吗?

PHP:

代码语言:javascript
复制
$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

代码语言:javascript
复制
{!! 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:

代码语言:javascript
复制
    $('.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() {

        });

    });
EN

回答 1

Stack Overflow用户

发布于 2018-10-11 08:46:46

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

代码语言:javascript
复制
var image = $('.image').prop('files')[0];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52750433

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档