使用AJAX发送文件数组 [英] Send array of files using AJAX

查看:54
本文介绍了使用AJAX发送文件数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个包含一些图像的数组:

Say I have an array which contains a few images:

var images = [image1, image2, image3]

如何在单个请求中使用AJAX将这些图像发送到php文件?

How do I send these images to a php file using AJAX in a single request?

以下代码不起作用:

$.ajax({
    url: 'PHP/posts.php',
    type: 'post',
    data: {data: images},
    success: function(data) {
      alert(data);
      location.reload();
    }
  });

我的HTML:

<div id="newPostFile">
    <label for="newPostFiles"><i class="fa fa-file-text-o" id="newPostFileIcon" aria-hidden="true"></i></label>
    <input type="file" name="newPostFiles" id="newPostFiles">
</div>

目标:只要选择了文件时,该文件被添加到所述阵列,并且当按钮被点击提交,所有文件都在一次上传.

Endgoal: Whenever a file is selected, the file is added to the array and when the submit button is clicked, all the files are uploaded at once.

推荐答案

您必须将文件作为formData发送

You have to send files as formData

var images = [image1, image2, image3]
var data   = new FormData();

images.forEach(function(image, i) {
    data.append('image_' + i, image);
});

$.ajax({
    url: 'PHP/posts.php',
    type: 'post',
    data: data,
    contentType: false,
    processData: false,
    success: function(data) {
       console.log(data);
       location.reload();
    }
});

但是无论如何您都在重新加载页面时,为什么还要使用ajax?

But as you're reloading the page anyway, why use ajax at all ?

这篇关于使用AJAX发送文件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆