简体   繁体   中英

Is it possible to fake a multipart/form-data post with a jquery ajax call?

I want to be able to post a multipart/form-data message back to the server. Now I know I can't send a file directly with an ajax call and I dont want to send any actual file. I want to format the post so that it simulates a file transfer with this is the file data string as if it were the file's contents and test.txt as if it were the file name.

For example on the backend (php) I want to use echo $_FILES['uploadedfile']['name'] and see test.txt .

I assume I'll have to muck with the headers being sent but not sure exactly what I have to set. I also assume I'll have to treat the fake file data differently than the rest of the data I'm sending over the ajax call. Right now my ajax call looks like this:

        $.ajax({
            beforeSend: function(req) {
                req.setRequestHeader("Accept", '');
                req.setRequestHeader("Accept", $('#type').val());
            },
            'url': $('#url').val(),
            'type': $('#verb').val(),
            'data': data,
            'mimeType': 'multipart/form-data',
            'complete': function (jqXHR, textStatus) {
                var msg = "Data: " + dump(data);
                msg += "<br /><br />Status: " + jqXHR.status + " (" + jqXHR.statusText + " - " + textStatus + ")<br />";
                msg += jqXHR.getAllResponseHeaders().replace(/\n/g, "<br />");
                msg += "---<br />" + jqXHR.responseText;
                $('#results').html(msg);
            }
        });

您可以使用FormData修补jquery, https://github.com/francois2metz/html5-formdata并查看此问题, 使用jQuery.ajax发送multipart / formdata

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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