2

我通过 jquery ajax 请求向 laravel 发送多个输入。

这是我的脚本

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

           });

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

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],而是我想要的所有文件对象。

我在哪里犯错。

4

1 回答 1

0

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

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

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

在我选择具有该属性的文件之前,.files但遵循此问题如何使用 jQuery.ajax 和 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);

我希望这个答案可以在未来帮助其他任何人,或者至少再次帮助我自己。

于 2018-03-13T04:27:49.503 回答