通过AJAX调用时,$ _FILES不会填充文件 [英] $_FILES is not populated with file when called through AJAX

查看:118
本文介绍了通过AJAX调用时,$ _FILES不会填充文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用简单的ajax调用来提交表单数据,我试图将一些表单输入和文件一起发送。

I am using simple ajax call to submit form data where I am trying to POST some form inputs along with an file.

    $("#submit-uploaded-audio").on("click", function () {
    var post_data = new FormData();
    var file = $("#audio_file").prop('files')[0];

    post_data.append('key1', 'value1');
    post_data.append('key2', 'value2');
    post_data.append('file', file);

    $.ajax({
        url: "/process_audio_upload",
        type: "POST",
        data: post_data,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data) {
            console.log(data);
            // some logic
        },
        error: function(error) {
            // some logic here
        }
    });
});

Ajax调用转到服务器url(codeigniter框架),但在调用中发布的数据不是填充$ _POST以及$ _FILES(两个数组都为空)

Ajax call goes to the server url (codeigniter framework) but data posted in call is not getting populated into $_POST as well as $_FILES (both arrays are empty)

检查php.ini设置和文件上传设置看起来不错

Checked php.ini settings and file upload settings looks good

但是,php:// input以原始格式显示所需数据

However, "php://input" shows required data in raw format

var_dump(file_get_contents("php://input"));

我想将这些数据分别放到$ _POST和$ _FILES数组中,以便我可以做进一步的操作。

I want to get this data into respective $_POST and $_FILES array so that I can do further actions.

提前致谢。

还尝试了以下解决方案

https://stackoverflow.com/a/10899796/4349933

https://stackoverflow.com/a/10899796/4349933

推荐答案

它可能与 post_data 变量有关,因为你创建一个空的 FormData 然后它可能试图通过 jQuery append ,用于附加HTML元素...

It may be related to the post_data variable being empty, since you are creating an empty FormData and then it may be attempting to append through jQuery append, which was designed to append HTML elements...

尝试简单地执行:

post_data.key1 = 'value1';
post_data.file = file;
console.log(post_data);

这应该返回:

FormData {key1: "value1", file: {...}}

如果 FormData.append 无法正常工作,我尝试不仅仅使用jQuery进行测试并执行 Javascript默认请求

由于 post_data 似乎没问题,所以请通过其他网站执行POST请求(例如 hurl.it )使用相同的URL,即 yourdomain.here/process_audio_upload 。如果没有任何回复,则可能是URL路由问题。

Since the post_data seems to be alright, then perform a POST request through another website (e.g. hurl.it) by using the same URL, i.e. yourdomain.here/process_audio_upload. If nothing comes back, it's likely that the URL routing is the issue.

这篇关于通过AJAX调用时,$ _FILES不会填充文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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