使用Ajax通过模式上传文件 [英] File upload through a modal using Ajax

查看:99
本文介绍了使用Ajax通过模式上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Ajax通过模式上传文件.我该怎么办?

I want to upload a file through a modal using Ajax. How can I do that?

我的模态:

<div id="addBtn" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h5 class="modal-title" id="myModalLabel">Add a medicine</h5>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label class="control-label mb-10">Generic Name</label>
            <select class="form-control" name="medicine_id" id="medicine_id">
              @foreach($items as $item)
              <option value="{{$item->id}}" >{{$item->generic_name}}</option>
              @endforeach
            </select>
          </div>

          <div class="form-group">
            <label class="control-label mb-10">Dosage Volume</label>
            <input type="text" name="dosage_name" id="dosage-volume" class="form-control" placeholder="Example: 20mg">
          </div>

          <div class="form-group">
            <label class="control-label mb-10">Form</label>
            <input type="text" name="form" id="form" class="form-control" placeholder="Bottle, Tablet">
          </div>

          <div class="form-group">
            <label class="control-label mb-10">Price Per piece</label>
            <input type="text" name="price" id="price" class="form-control" placeholder="Price">
          </div>

          <div class="form-group">
            <label class="control-label mb-10">Insert a photo</label>
            <div class="panel-wrapper collapse in">
              <div class="panel-body">
                <div class="mt-20">
                  <input type="file" name="photo" id="input-file-now" class="dropify" >
                </div>  
              </div>
            </div>
          </div>

        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-success waves-effect" data-dismiss="modal" id="save-dosage">Save</button>
        <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Cancel</button>
      </div>

    </div>
    <!-- /.modal-content -->
  </div>
</div>

这是我的JavaScript文件:

This is my JavaScript file:

function addDosage(url){
    console.log(url);

    $.ajax({
        type:'POST',
        url:url,
        data:{
            'medicine_id' : $('select#medicine_id').val(),
            'dosage-volume' : $('#dosage-volume').val(),
            'form'  : $('[name=form]').val(),
            'price' : $('[name=price]').val(),
            'photo' : $('[name=photo]').val()
        },
        success:callback,
        error:err
    })

}


function callback(data){
    console.log(data);
}


function err(xhr, reason, ex)
{
    console.log(+xhr.status);
}

这是我的控制器:

 public function storeDosage(ProductsRequest $request){
    $file = $request->file('photo');
    $fileName = uniqid() . $file->getClientOriginalName();

    if(!file_exists('medicine/images')){
      mkdir('medicine/images', 0777, true);
    }
    $file->move('medicine/images', $fileName); 
    if(!file_exists('medicine/images/thumbs')){
      mkdir('medicine/images/thumbs', 0777, true);
    }

    $thumb = Image::make('medicine/images/' .$fileName)->resize(150,150)->save('medicine/images/thumbs/' . $fileName,50);
        //post information to db
    $dosage = $this->dosage;
    $dosage->dosage_name = $request['dosage_name'];
    $dosage->form = $request['form'];
    $dosage->medicine_id = $request['medicine_id'];
    $dosage->price = $request['price'];
    $dosage->save();

    $image = $dosage->photo()->create([
      'dosage_id' => $request->input('id'),
      'file_name' => $fileName,
      'file_size' => $file->getClientSize(),
      'file_mime' => $file->getClientMimeType(),
      'file_path' => 'medicine/images/thumbs'. $fileName,
      'created_by'=> auth()->user()->id,
      ]);
    return redirect()->route('medicineList');

  }

但是它返回错误500.我认为Ajax不接受使用Bootstrap模态的文件上传.

but it returns error 500. I think Ajax doesn't accept file upload using Bootstrap modal.

推荐答案

您可以像这样通过ajax使用引导程序模式上载文件.

You can upload the file using bootstrap modal via ajax like this.

在您的表单标签中,使用属性enctype和html表单如下:

In your form tag use attribute enctype and form html will be like below:

 <form enctype="multipart/form-data" id="modal_form_id"  method="POST" >
    <input type="file" name="documents">
 </form>

Js代码:

    var postData = new FormData($("#modal_form_id")[0]);

                         $.ajax({
                                 type:'POST',
                                 url:'your-post-url',
                                 processData: false,
                                 contentType: false,
                                 data : postData,
                                 success:function(data){
                                   console.log("File Uploaded");
                                 }

                              });

在控制器端,您可以执行以下功能来上传图像.

On your controller side you can do in the function like below to upload image.

    if(Input::hasFile('documents')) {

        $path = "directory where you wish to upload file";

        $file_name= Input::file('documents');   
        $original_file_name = $file_name->getClientOriginalName();

        $extension       = $file_name->getClientOriginalExtension();
        $fileWithoutExt  = str_replace(".","",basename($original_file_name, $extension));  
        $updated_fileName = $fileWithoutExt."_".rand(0,99).".".$extension; 

        $uploaded = $file_name->move($path, $updated_fileName);

        echo $updated_fileName;

    }

这篇关于使用Ajax通过模式上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆