AJAX/Laravel多个文件上传 [英] AJAX/Laravel Multiple File Uploads

查看:50
本文介绍了AJAX/Laravel多个文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery/AJAX/Laravel的拖放事件上传多个文件.

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

我的下落事件:

$( 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)
      }
    }
  });

我的上传脚本:

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

我的控制器代码:

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:

因此,CSRF令牌通过了,图像(我认为是)通过了.我的问题是使用PHP访问文件并通过-> store();将其存储.

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');

但是,我不了解这种照片"方面.如果上传了视频或PDF,该怎么办?我基本上不了解如何访问请求对象的不同部分.Laravel网站上的文档对此非常稀疏,仅提供了一个使用照片"的示例,但从未说明.

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.

推荐答案

弄清楚了.

在我的上载控制器中:

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

这篇关于AJAX/Laravel多个文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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