【问题标题】:How to get multiple image file / data in controller of laravel如何在 laravel 的控制器中获取多个图像文件/数据
【发布时间】:2017-04-19 09:12:57
【问题描述】:

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

我哪里出错了。

【问题讨论】:

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


    【解决方案1】:

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

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

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

    在我选择具有.files 属性的文件之前,但在此问题How to upload a file using jQuery.ajax and FormData 中遵循 cmets,它们表明您实际上应该使用 .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);
    

    我希望这个答案可以在未来对其他人有所帮助,或者至少对我自己有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-09-09
      • 1970-01-01
      • 2021-06-29
      • 2021-10-10
      • 1970-01-01
      • 2019-07-10
      • 1970-01-01
      • 2019-11-06
      • 2018-09-26
      相关资源
      最近更新 更多