如何在laravel控制器中获取多个图像文件/数据

时间:2017-04-19 09:12:57

标签: jquery laravel-5.3 multiple-file-upload

我发送了多个输入到laravel thorugh jquery ajax请求。

这是我的脚本

jqyery脚本:

var album_file=document.getElementById("upload_file").files;//getting multiple images

var albumname = document.getElementById('albumname').value;//albumname
 console.log(album_file);

 $.get('/photoalbum/?albumdetail='+album_file+'&albumname='+albumname,function(data){
              console.log(data);

           });

上传bitton脚本的onclick执行,我在专辑文件的控制台上获取数据

FileList {0: File, 1: File, length: 2}
length:2
0:File
  lastModified:1489731759920
  lastModifiedDate:Fri Mar 17 2017 11:52:39 GMT+0530 (India Standard    Time)
  name:"1.png"
  size:117627
  type:"image/png"
  webkitRelativePath:""
__proto__:
    File
    1:File

当我在laravel控制器上接收请求时,在下面的表格中

  public function storealbum(Request $request)
{
   print_r($request::all());

}

并打印:

Array ( [albumdetail] => [object FileList] [albumname] => tet )

我想要的不是[object FileList]我想要的所有文件对象。

我犯了错误。

1 个答案:

答案 0 :(得分:0)

我知道这是一个古老的话题,但我遇到了同样的错误。

这个问题的解决方案包括两件事:

首先,发送并选择实际文件

在我选择包含属性.files的文件但是按照此问题How to upload a file using jQuery.ajax and FormData中的评论之前,他们表示您应该使用.files[0]实际执行该操作,以便发送实际选中的内容文件。

其次,AJAX调用应排除流程数据和内容类型

在同一个问题How to upload a file using jQuery.ajax and FormData中,它们表明您应该为AJAX调用添加两个参数,以避免修改数据:processData:falsecontentType:false这里是示例代码他们使用:

$.ajax({
   url: "upload.php",
   type: "POST",
   data: formData,
   processData: false,
   contentType: false,
   success: function(response) {
       // .. do something
   },
   error: function(jqXHR, textStatus, errorMessage) {
       console.log(errorMessage); // Optional
   }
});

formData应该像这样初始化:

let formData = new FormData();
//And then include the attachments, can be just one file or an array of them
//The first parameter is the name of the field and the second one is just the data
formData.append('attachments', attachments_array);

我希望这个答案可以帮助将来的其他人,或者至少可以帮助我。