dongyou7472 2018-05-09 06:34
浏览 189
已采纳

Jquery文件上传在Laravel中不起作用

I have tried majority of other questions here and other solutions and nothing has worked so far.

What I am trying to accomplish is upload images before Laravel's validation takes place, obviously I can't use the create function because it wont be hit until validation succeeds so I have made a custom function to do the file saving server side and trying to use Ajax to call that function every time a file is selected.

Current issue: doesn't seem like my Ajax is running on debugging its being skipped over,

second issue: I have a csrf token in my master template do i still need to add the ajax setup? if so is the way i am doing it correct.

Route:

Route::post('/upload', 'UploadController@uploadSubmit');

View:

<div>
    <input type="file" id="fileupload" name="photos[]" data-url="/upload" multiple />
    <br />
    <div id="files_list"></div>
    <p id="loading"></p>
    <input type="hidden" name="file_ids" id="file_ids" value="" />                    
 </div>

Ajax call:

  $(document).ready(function(){ 
    $("input").change(function(){
         alert('triggered');

         debugger;
         $('#fileupload').fileupload({

           $.ajaxSetup({
              headers: {
              'X-CSRF-TOKEN': $(meta[name="csrf-token"]).attr('content')
              }
              dataType: 'json',
              add: function (e, data) {
                  $('#loading').text('Uploading...');
                  data.submit();
              },
              done: function (e, data) {
                  $.each(data.result.files, function (index, file) {
                      $('<p/>').html(file.name + ' (' + file.size + ' KB)').appendTo($('#files_list'));
                      if ($('#file_ids').val() != '') {
                          $('#file_ids').val($('#file_ids').val() + ',');
                      }
                      $('#file_ids').val($('#file_ids').val() + file.fileID);
                  });
                  $('#loading').text('');
              }
            });
         });
      });
   });

Controller:

 public function uploadSubmit(Request $request){

        $files = [];
        dd(request());
       foreach($learnerFiles as $key => $learnerFile){   
           if(count($learnerFile) > 0){

                $path = $learnerFile->storeAs('public/uploads/learners', request('idNumber').'_'.$key.'.'.$learnerFile->extension());
                $search = 'public/' ;
                $trimmed = str_replace($search, '', $path) ;
                //dd($learnerFiles);
                $file = FileUpload::create([

                    'user_id'     => $learner->id,
                    'file_name'   => $key,
                    'path'        => $trimmed
                ]);
            }
            else{

            }

        $file_object = new \stdClass();
        $file_object->name = $key;
        $file_object->size = round(Storage::size($path) / 1024, 2);
        $file_object->fileID = $learner->id;
        $files[] = $file_object;
        }

        return response()->json(array('files' => $photos), 200);        
    }
  • 写回答

1条回答 默认 最新

  • doutun9179 2018-05-09 07:11
    关注

    I'm using the following method to upload images using Ajax call and Laravel back-end.

        var uploader = $('#image-uploader[type="file"]');
        var data = new FormData();
        $.each(uploader.files, function() {
            data.append('image[]', this);
        });
        data.append('_token', $('[name="csrf-token"]').attr('content'));
        var url = '/upload'; //Or any target path with post method
        $.ajax({
            url: url,
            method: 'POST',
            data: data,
            processData: false,
            contentType: false,
            success: function(data) {
                alert('succeed');
            }
        });
    

    Consider you can access to image files in server-side using $_POST['image] array.
    Hope this helps you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮