使用JQuery AJAX发送包含文件和其他json表单数据的multipart / form-data

时间:2016-09-21 07:31:01

标签: javascript jquery ajax multipartform-data form-data

我有一个HTTP API,它等待具有以下结构的multipar / form-data消息:

--boundary
Content-Disposition: form-data; name=""Meta""
Content-Type: application/json

{""Title"":""title"",""Description"":""description"",""Number"":3}
--boundary
Content-Disposition: form-data; name=""file""; filename=""fileName""
Content-Type: text/plain
Content-Transfer-Encoding: 7BIT

some text content
--boundary

我正在尝试将消息的结构设为FormData,如下所示:

var data = new FormData();
 data.append("Meta", "Content-Type: application/json\r\n\r\n" + [JSON.stringify({ Title: "title", Description: "description", Number: 3})] + "\r\n");
data.append('File', document.getElementById("file").files[0]);

$.ajax({
    url: myservice,
    data: data,
    cache: false,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function (data, status, req) {
        alert("OK"+req);
    },
    error: function (req, status, error) {
        alert("ERROR"+req);
    }
});

但是我无法将内容类型添加到非文件部分。

通过这种方法,我在Content-Disposition和Content-Type之间发出了一条带有剩余分界线的消息。

-----------------------------10743159127866
Content-Disposition: form-data; name="Meta"

Content-Type: application/json

{"Title":"title","Description":"description","Number":3}

-----------------------------10743159127866
Content-Disposition: form-data; name="File"; filename="b839f0cc60ac4fb68f826b20cd02873b.pdf"
...

1 个答案:

答案 0 :(得分:0)

<script type="text/javascript">
$(document).ready(function() {
    $("#submit").click(function() {
        var fileInput = document.getElementById('image');
        var file = fileInput.files[0];
        var formData = new FormData();
        formData.append('file', file);
        $.ajax({
            url: "url.php",
            type: "POST",
            data: "file="+file,
            cache: false,

            success: function(res) {
                alert(res);
            },
            error: function(err){
                alert(err);
            }
        });
    }); 
});
</script>