使用Ajax通过模式上传文件

时间:2017-02-17 12:53:39

标签: jquery ajax laravel

我想使用Ajax通过模式上传文件。我怎么能这样做?

我的模态:

<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文件:

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模式上传文件。

1 个答案:

答案 0 :(得分:3)

您可以通过像这样的ajax使用bootstrap模式上传文件。

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

 <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");
                                 }

                              });

在控制器端,您可以使用以下功能上传图像。

    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;

    }