简体   繁体   English

AJAX使用包含文件的JSON对象发布到PHP

[英]AJAX Post to PHP with JSON Object containing a File

I'm trying to attach a file to an email that is inside of a JSON object being posted to my PHP script. 我正在尝试将文件附加到发布到我的PHP脚本的JSON对象内部的电子邮件中。

The posted JSON appears as: 发布的JSON显示为:

{  
   data:{  
      "sendto":"sendto@example.com",
      "name":"John Smith",
      "contem":"john.smith@example.com",
      "mess":"This is a test",
      "subj":"Test"
   },
   file:{  
      "webkitRelativePath":"",
      "lastModified":1389280265000,
      "lastModifiedDate":"2014-01-09T15:11:05.000Z",
      "name":"test.pdf",
      "type":"application/pdf",
      "size":6437
   }
}

My PHP handles all of the "data" attributes just fine, but when I try to check for the file, I get: 我的PHP处理所有“数据”属性就好了,但当我尝试检查文件时,我得到:

Notice:  Undefined index: file in My\Website\Location\script.php on line 20

And Line 20 is: 第20行是:

$file = $_FILES['file'];

Is this index undefined because it's within a JSON object? 此索引是否未定义,因为它位于JSON对象中?

I've also tried: 我也尝试过:

$file = $_FILES[json_decode(stripslashes($_POST['file']), true)];

Thinking since the file is within a JSON object, it first needs decoded. 由于文件在JSON对象中,因此首先需要解码。 However, this returned: 但是,这返回:

Warning:  Illegal offset type in My\Website\Location\script.php on line 20

I think the issue for the illegal offset had something to do with trying to set $_FILES to a JSON object, yes? 我认为非法偏移的问题与尝试将$ _FILES设置为JSON对象有关,是吗?

When I try to simply set the $_POST['file'] into the $_FILES array: 当我尝试简单地将$ _POST ['file']设置为$ _FILES数组时:

$file = $_FILES[$_POST['file']];

I receive: 我收到:

Notice:  Undefined index: {"webkitRelativePath":"","lastModified":1389280265000,"lastModifiedDate":"2014-01-09T15:11:05.000Z","name":"test.pdf","type":"application/pdf","size":6437} in My\Website\Location\script.php on line 20

Showing the uploaded file as a JSON object. 将上载的文件显示为JSON对象。

What am I missing here? 我在这里错过了什么? How can I get the uploaded file from my AJAX post? 如何从我的AJAX帖子中获取上传的文件?

ANSWER 回答

As noted about the multiform/form-data content type, I changed the way I sent the form data. 正如关于multiform / form-data内容类型所述,我改变了发送表单数据的方式。

Rather than using an object with a file inside of it: 而不是使用带有文件的对象:

var d = new FormData();
var data = {};
data.sendto = 'sendto@example.com';
data.name = $('#puName').val();
data.contem = $('#puEmail').val();
data.mess = $('#puMess').val();
data.subj = 'User Permissions';
d.append('data', JSON.stringify(data));
$.each($('#puFile')[0].files, function(i, file) {
     d.append('file-'+i, file);
});
sendEmail(d);

I sent a FormData object directly to the PHP script. 我将FormData对象直接发送到PHP脚本。

function sendEmail(d){
    $.ajax({
        url: "script.php",
        data: d,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function () {
            alert("Cool");
        },
        error: function (e) {
            alert("Not Cool");
        }
    });
}

The FormData was made of an JSON object for my data, and the selected File. FormData由我的数据的JSON对象和所选的File组成。

PHP then read the form data like: 然后PHP读取表单数据,如:

$data = json_decode(stripslashes($_POST['data']), true);
$file = $_FILES['file-0'];

Now my email is sending correctly. 现在我的电子邮件发送正确。

$_FILES superglobal will only be created when multipart/form-data content-type is set for the POST and would include the actual file being POSTed, not a local reference to that file. $_FILES superglobal仅在为POST设置multipart/form-data content-type时创建,并且包括POSTed的实际文件,而不是对该文件的本地引用。 Instead you are sending a JSON request (hopefully with an appropriate application/json content-type). 相反,您正在发送JSON请求(希望具有适当的application/json内容类型)。 This is not going to populate $_FILES . 这不会填充$_FILES Unless your receiving script has the ability to take the path information provided and access the file in question, your POSTing script will actually need to send the file as part of the POST. 除非您的接收脚本能够获取所提供的路径信息并访问相关文件,否则您的POSTing脚本实际上需要将该文件作为POST的一部分发送。

Uploading files via AJAX is best handled using specific AJAX upload libraries that are meant to do this, which basically utilize workarounds to the fact that you really can't POST a file asynchronously natively in browsers. 通过AJAX上传文件最好使用特定的AJAX上传库来处理,这些库基本上使用了变通方法,因为您实际上无法在浏览器中本地异步POST文件。

Have you tried something like this - 你尝试过这样的事 -

Copy the json code in a variable say 'a' and then, decode it ie json_decode(a), then a->file 将json代码复制到一个变量'a'然后解码它,即json_decode(a),然后a-> file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM