weixin_33682790 2016-01-24 13:03 采纳率: 0%
浏览 23

通过ajax上传文件

I'm trying this for days now! Nothing that seemed to work for others, worked for me! And I really have to have it done now.

So this is very basic:

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="browseFile" id="photo" />
    <input type="submit" id="send" />
</form>

As you can see, there is a HTML form with a file input and a submit button. For what I'm trying to make, I need to send the file from the input field instantly after changing the value of it to the server.

Let's skip the part of the event listeners and validation.

This is the javascript, that should be able to get the value of the input field and send it to the server:

var inputFilePhoto = document.getElementById("photo");
var imageFile = inputFilePhoto.files[0];

var formData = new FormData();             
formData.append("file", imageFile);

$.ajax({
    type: "POST",
    url: "ajax.php",
    data: formData,
    contentType: false,
    processData: false,

    success: function (output) {
        document.write(output);
        alert("OK");
    },
    error: function () {
        alert("Error");
    }
});

As you can see, I'm using the FormData object, which was new for me a couple days ago. It works fine with text fields etc., but not for file input fields. I also tried to apply the whole form on this object (new FormData($("form")[0])), but this - again - ignored the input fields of type "file" as if they did not exist.

To come back to the example above: ajax.php does nothing than debugging $_POST. So this is ajax.php:

<?php

echo '<pre>';

var_dump($_POST);
echo '</pre>';

The result of this is an empty array array(0) { }

Technical details: Tested on Chrome v48 on Mac OS X 10.11, using jQuery 2.2.0

I hope someone can finally help me with this, I accept solutions that use js plugins too.

  • 写回答

1条回答 默认 最新

  • weixin_33736048 2016-01-24 13:04
    关注

    Data from file inputs appears in the $_FILES superglobal, not $_POST, when form data is parsed by PHP.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分