【问题标题】:Laravel upload image through modal not workingLaravel通过模态上传图像不起作用
【发布时间】:2019-09-24 14:44:10
【问题描述】:

我在 laravel 中制作库存系统,我想上传我拥有的每件产品的图片。我的问题是我无法上传图片。我在上传照片时尝试了我的旧代码,但它在我当前的项目中不起作用。您在控制器中看到的上传代码是 laravel 集体形式。但现在,我正在使用模式和 ajax 请求将输入保存到数据库中。有人可以知道我该怎么做吗?顺便说一句,我的模态没有表单标签,因为我认为表单在模态中不起作用。提前致谢!

模态创建。

     <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered" role="document">
                      <div class="modal-content">
                        <div class="modal-header">
                          <h5 class="modal-title" id="exampleModalCenterTitle">Register New Product</h5>
                          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                          </button>
                        </div>
                        <div class="modal-body">
                        <p style="font-weight: bold;">Name </p>
                          <input   type="text" class="form-control" id="product_name"/>
                          <p style="font-weight: bold;">Description </p>
                          <input   type="text" class="form-control" id="description"/>

                          <p style="font-weight: bold;">Price </p>
                          <input   type="text" class="form-control" id="currentprice"/>
                          {{-- <input style="text-transform:uppercase"   type="text" class="form-control" id="supplier_id"/> --}}
                          <p style="font-weight: bold;">Supplier </p>
                          <select class="form-control"  id="supplier_id"  >
                              @foreach ($suppliers as $supplier)
                          <option value="{{$supplier->id}}">{{$supplier->name}}</option>
                              @endforeach
                              </select>
                         <p style="font-weight: bold;">Picture </p>
                          <input  type="file" class="form-control" id="picture"/>
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                          <button type="button" class="btn btn-primary" id="add_product">Add</button>
                        </div>
                      </div>
                    </div>
                  </div>

控制器

    public function store(Request $request)
    {
        $data = $request->all();
        $data['product_name'] = ($data['product_name']);
        $data['description'] = ($data['description']);
        $data['supplier_id'] = ($data['supplier_id']);
        $data['price'] = ($data['price']);



        if ($request->hasFile('image')){
            //Add new photo
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location = public_path('img/' . $filename);
                Image::make($image)->resize(300,300)->save($location);
                $oldFilename = $products->image;
            //Update DB
                $products->image = $filename;
             //Delete the old photo
                // Storage::delete($oldFilename);
            }

        Product::create($data);
        return response()->json($data);
    }

阿贾克斯

   $(document).ready(function(){
                //add
                $('#add_product').click(function(e){
                    e.preventDefault();
                    var name = $('#product_name').val();
                    var description = $('#description').val();
                    var price = $('#currentprice').val();
                    var supplier_id = $('#supplier_id').val();
                    var image = $('#picture').val();

                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });

                    $.ajax({
                        url: "{{    url('/product')     }}",
                        method: 'post',
                        data:{
                            product_name: name,
                            description: description,
                            price: price,
                            supplier_id: supplier_id,
                            image: image,
                        },
                        success: function (res){
                            console.log(res);
                            window.location.href = '{{route("products")}}'
                        }
                    });

                });
                //add

型号

class Product extends Model
{
    use SoftDeletes;
    protected $fillable = [
        'product_name', 'quantity', 'description' ,'supplier_id', 'price', 'image',
    ];

    public function supplier()
    {
        return $this->hasOne('App\Supplier');
    }
}

【问题讨论】:

  • 在定义 image 变量的 Ajax 代码中
  • 好的,先生,我想我忘了定义image 变量。一分钟后告诉你结果是什么
  • 先生,当我添加此代码var image = $('#picture').val(); 时没有错误,当我查看数据库时,图像名称是这样的`C:\fakepath\59838793_482825115589519_4600609237641461760_n.jpg`。而且我的public/img 目录中没有图片

标签: javascript php jquery ajax laravel


【解决方案1】:

我不能添加评论,那是愚蠢的......

您还可能需要在 json 中编码图像数据。

How do you put an image file in a json object?

(固定措辞)

【讨论】:

  • 您可以尝试将这些添加到您的 Ajax, enctype: 'multipart/form-data', processData: false, contentType: false
  • 第一个告诉服务器你有一个混合数据正在提交。 processData 告诉 query 不要“处理”正在发送的数据, contentType 告诉 jquery 不要更改类型。
  • 啊,我明白了。我把你想要我的代码,现在它返回一个错误。我不能再插入了
  • 我的控制器 store 方法中的错误是 Undefined index: product_name。我觉得没什么问题
  • 没问题。我相信你会弄明白的。
猜你喜欢
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多