XMLHttpRequest: Multipart/Related POST with XML and image as payload

前端 未结 1 1502
Happy的楠姐
Happy的楠姐 2020-12-03 00:04

I\'m trying to POST an image (with Metadata) to Picasa Webalbums from within a Chrome-Extension. Note that a regular post with Content-Type image/xyz works, as I described h

1条回答
  •  执笔经年
    2020-12-03 00:47

    The XMLHttpRequest specification states that the data send using the .send() method is converted to unicode, and encoded as UTF-8.

    The recommended way to upload binary data is through FormData API. However, since you're not just uploading a file, but wrapping the binary data within XML, this option is not useful.

    The solution can be found in the source code of the FormData for Web Workers Polyfill, which I've written when I encountered a similar problem. To prevent the Unicode-conversion, all data is added to an array, and finally transmitted as an ArrayBuffer. The byte sequences are not touched on transmission, per specification.

    The code below is a specific derivative, based on the FormData for Web Workers Polyfill:

    function gen_multipart(title, description, image, mimetype) {
        var multipart = [ "..." ].join(''); // See question for the source
        var uint8array = new Uint8Array(multipart.length);
        for (var i=0; i

    The script becomes more efficient when you use .readAsArrayBuffer instead of .readAsBinaryString:

    function gen_multipart(title, description, image, mimetype) {
        image = new Uint8Array(image); // Wrap in view to get data
    
        var before = ['Media ... ', 'Content-Type:', mimetype, "\n\n"].join('');
        var after = '\n--END_OF_PART--';
        var size = before.length + image.byteLength + after.length;
        var uint8array = new Uint8Array(size);
        var i = 0;
    
        // Append the string.
        for (; i

    0 讨论(0)
提交回复
热议问题