无法上传多个文件

时间:2016-07-11 14:39:32

标签: php laravel laravel-5 xmlhttprequest

可以保存单个文件,但是,多个文件似乎没有从$ request-> file()获得正确的数组,并且foreach失败。

客户

$scope.setFiles = function(element) {
    $scope.$apply(function($scope) {
      console.log('files:', element.files);
      // Turn the FileList object into an Array
        $scope.files = []
        for (var i = 0; i < element.files.length; i++) {
          $scope.files.push(element.files[i])
        }
      $scope.progressVisible = false
      });
    };

    $scope.uploadFile = function() {
        var fd = new FormData()
        for (var i in $scope.files) {
            fd.append("file", $scope.files[i])
        }

        var boundary=Math.random().toString().substr(2);

        var xhr = new XMLHttpRequest()
        xhr.upload.addEventListener("progress", uploadProgress, false)
        xhr.addEventListener("load", uploadComplete, false)
        xhr.addEventListener("error", uploadFailed, false)
        xhr.addEventListener("abort", uploadCanceled, false)
        xhr.open("POST", "/fileupload",true)
        $scope.progressVisible = true
        xhr.setRequestHeader("X-CSRF-TOKEN", csrftoken);
        xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');

        // xhr.setRequestHeader("content-type","multipart/form-data; charset=utf-8; boundary=" + boundary);        
        xhr.send(fd)
    }

Laravel

public function fileUpload(Request $request)
{


    $files = $request->file('file');


    $file_count = count($files);

    echo $file_count;

   foreach ($files as $file) {

        $oname = $file->getClientOriginalName();
        $filename = $oname.'.'.$file->getClientOriginalExtension();

        $file->move(
            base_path() . '/uploads/applicants/', $filename
            );

    }



}

2 个答案:

答案 0 :(得分:0)

请改用$request->allFiles(),它会返回请求中所有文件的数组:

foreach ($request->allFiles() as $file) {
    //You code here !
}

答案 1 :(得分:0)

您必须进行两项更改:

  1. 将$ scope.files移出$ scope.SetFile
  2. 方法

    enter image description here

    1. 将文件转换为数组参数
    2. enter image description here