duanmiao6695 2017-03-13 01:51
浏览 89
已采纳

AJAX / Laravel多文件上传

I'm trying to upload multiple files from a drag/drop event using jQuery/AJAX/Laravel.

MY DROP EVENT:

$( document ).on('drop dragleave', '.file-drag', function(e){
    $(this).removeClass('drop-ready');
    if(e.originalEvent.dataTransfer.files.length) {
      e.preventDefault();
      e.stopPropagation();

      if (e.type === "drop") {
      var files = e.originalEvent.dataTransfer.files;
      AjaxFileUpload(files)
      }
    }
  });

MY UPLOAD SCRIPT:

function AjaxFileUpload(files){
    console.log(files);

    //Start appending the files to the FormData object.
    var formData = new FormData;
    formData.append('_token', CSRF_TOKEN);
    for(var i = 0; i < files.length; i++){
      formData.append(files[i].name, files[i])
    }

    console.log(formData.entries());

    $.ajax({
        //Server script/controller to process the upload
        url: 'upload',
        type: 'POST',

        // Form data
        data: formData,

        // Tell jQuery not to process data or worry about content-type
        // You *must* include these options!
        cache: false,
        contentType: false,
        processData: false,
        // Error logging
        error: function(jqXHR, textStatus, errorThrown){
          console.log(JSON.stringify(jqXHR));
          console.log('AJAX Error: ' + textStatus + ": " + errorThrown);
        },
        // Custom XMLHttpRequest
        xhr: function() {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                // For handling the progress of the upload
                myXhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        $('progress').attr({
                            value: e.loaded,
                            max: e.total,
                        });
                    }
                } , false);
            }
            return myXhr;
        },
        success: function(data){
          console.log(data);
        }
    });
  }

MY CONTROLLER CODE:

class UploadsController extends Controller
{
    public function UploadFiles(Request $request){
      return $request->all();
    }
}

I THINK my images are getting to the server side, as when I return the request object, I get the following in console:

enter image description here

Thus, the CSRF token is getting through, and the images (I think?) are getting through. My problem from here is accessing the files with PHP and storing them via ->store();.

In the countless examples online/documentation, they typically use something along the lines of:

$path = $request->photo->store('images');

However, I don't understand the 'photo' aspect of this. What if a video or a PDF is uploaded? I basically don't understand how I am to access the different parts of the request object. Documentation on Laravel site is pretty sparse for this and only gives an example using 'photo' of which it never explains.

  • 写回答

3条回答 默认 最新

  • dsdapobp26141 2017-03-14 23:47
    关注

    Figured it out.

    In my uploadscontroller:

    class UploadsController extends Controller
    {
        public function UploadFiles(Request $request){
          $arr = [];
          foreach($request->all() as $file){
            if(is_file($file)){
              $string = str_random(16);
              $ext = $file->guessExtension();
              $file_name = $string . '.' .  $ext;
              $filepath = 'uploads/' . Auth::user()->username . '/' . $file_name;
              $file->storeAs(('uploads/' . Auth::user()->username), $file_name);
              array_push($arr, [$file_name, $filepath]);
            }
    
          }
          return $arr;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。