在 Laravel 控制器中获取多个图像文件/数据的方法

11 浏览
0 Comments

在 Laravel 控制器中获取多个图像文件/数据的方法

我通过jquery的ajax请求将多个输入发送给laravel。\n以下是我的脚本:\njqyery脚本:\n

var album_file=document.getElementById("upload_file").files;//获取多个图片
var albumname = document.getElementById('albumname').value;//相册名
 console.log(album_file);
 $.get('/photoalbum/?albumdetail='+album_file+'&albumname='+albumname,function(data){
              console.log(data);
           });

\n在点击上传按钮时,脚本执行,并且我在相册文件的控制台上得到以下数据:\n

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

\n当我在laravel控制器上接收请求时,在下面的形式中:\n

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

\n它打印出:\n

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

\n我想要的是,而不是[object FileList],我要获得所有的文件对象。\n我犯了什么错误。

0
0 Comments

问题的出现原因是在上传多个图像文件/数据时,出现了错误。给出的解决方法是,首先需要使用.files[0]选择实际的文件来发送,而不是使用.files。其次,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);

希望这个答案能够帮助其他人,或者再次帮助我自己。

0