Javascript - 如何将图像数据(字节数组)添加到多部分POST请求

时间:2014-11-11 12:25:42

标签: javascript image file-upload bytearray multipartform-data

我在Javascript中使用AJAX发送多部分POST请求,我需要在请求中添加图片:

--0xKhTmLbOuNdArY-27f7edea-e541-485f-9bfe-bf9e10b2d6a7
Content-Disposition: form-data; name="uploadedFile"; filename="uploaded-image-a4784b4e-802a-4bed-8fc9-c2a5e038e04f.jpg"
Content-Type: image/jpeg

[Image Data Here]
--0xKhTmLbOuNdArY-27f7edea-e541-485f-9bfe-bf9e10b2d6a7--

我将图像作为字节数组,但是直接添加它并不起作用,我尝试将每个字节转换为其字符代码并将其附加到请求但是它也没有工作,图像会上传但是当我检索它时图像已损坏。

有关如何在不导致版本损坏的情况下附加图像数据的任何想法?

1 个答案:

答案 0 :(得分:0)

一种方法是将HTML5 BlobXMLHttpRequest一起使用;像这样:

// Utility to create a random string for multipart boundary
function randomString() {
    var str = '';
    for (var i = 0; i < 4; i++) {
        str += (Math.random().toString(16)+"000000000").substr(2,8);
    }
    return str;
}

function upload(filename, contentType, byteArray, success, error) {
    var file = document.getElementById("file").files[0];
    var boundary = randomString();

    var blob = new Blob([
        "--boundary_" + boundary + "\n"
        + "Content-Type: " + contentType + "\n" 
        + "Content-Disposition: form-data; name=\"uploadedFile\"; filename=\"" + filename + "\"\n\n",
        byteArray,
        "\n\n" 
        + "--boundary_" + boundary + "--"
    ], {type : "multipart/form-data; boundary=\"boundary_" + boundary + "\""});

    var request = new XMLHttpRequest();
    request.open("POST", url);

    request.onreadystatechange = function() {
        // if the upload is completed
        if (request.readyState == 4) {
            // if HTTP status is "Created"
            if (request.status == 201) {
                // return the response
                success(request.response);
            } else {
                // return the request, which has status, statusText etc
                error(request);
            }            
        }
    };

    request.send(blob);
}