【问题标题】:Ajax File Upload to php class [duplicate]Ajax文件上传到php类[重复]
【发布时间】:2014-01-16 19:24:24
【问题描述】:

我正在尝试将使用 ajax 发布的文件上传到面向对象的类,但它没有正确发布。

这里是ajax

 var handleUpload = function(event)
 {


event.preventDefault();
event.stopPropagation();

var fileInput = document.getElementById('file');

var data = new FormData();

for(var i = 0; i < fileInput.files.length; i++)
{

    data.append('file[]', fileInput.files[i]);

}

var request = new XMLHttpRequest();

request.upload.addEventListener('progress', function(event)
{


});

request.upload.addEventListener('load', function(event)
{


});

request.upload.addEventListener('error', function(event)
{


});

request.open('POST', 'profile.php');
request.setRequestHeader('Cache-Control', 'no-cache');
request.send(data);

   }

   window.addEventListener('load', function(event)
   {

var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);

   });

这是调用我创建的类中的函数的 php 代码。 javascript 成功发布,但 $_FILES 数组未设置,因此 php if 语句未运行。

if(!empty($_FILES['file']) && isset($_POST['special']))
{
    $special = $_POST['special'];
    $date = $_POST['date'];
    $user->postSpecial($special, $date, $_FILES);

}

【问题讨论】:

  • 我感觉这个问题已经被问了一千次了。你在 SO 中第一次检查它吗?
  • 没有一个接近我的问题
  • @user2872510,怀疑

标签: javascript ajax


【解决方案1】:

您的 AJAX 调用失败,因为您无法异步提交文件*。这就是为什么$_FILES 是空的。您可以(并且应该)做的是使用所谓的 iframe 表单 post hack(或切换到 jquery 和 jquery file upload plugin)。

* 地址为XMLHttpRequest2。浏览器支持见http://caniuse.com/#feat=xhr2

【讨论】:

【解决方案2】:

将表单发布到隐藏的 iframe

正如@nietonfir 所述,您不能只使用 XMLHTTPRequest 发布带有 input=file 的表单。但是,当 XHR2 不可用(或者您不想使用它)时,一种常见的解决方法是将表单发布到页面上的隐藏 iframe。有许多 JavaScript 库/jQuery 插件等为此提供了抽象(参见 https://github.com/Widen/fine-uploader 仅一个示例),但概念相当简单。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-08-15
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 2012-04-22
  • 2014-03-22
  • 2012-06-05
  • 2017-08-07
相关资源
最近更新 更多