5

我正在尝试使用 javascript 在批量请求中将多个图像上传到谷歌云存储。我使用https://developers.google.com/storage/docs/json_api/v1/how-tos/batch#example作为参考。

我有一个输入文件,用户可以在其中选择多个文件,还有一个“上传”btn 来上传到 GCS,如下所示:

<input type="file" name="fileName" id="fileInput" multiple="multiple" onchange="javascript: loadFiles()"/> 
<input type="button" name="upload-btn" id="upload" value="Upload"/>

当用户选择图像时,“loadFiles”函数会创建批处理请求的“正文”。

var tok = <token>;
var boundary = "---======= foo_bar_baz12034245623562346 ===";
var consolidated_request = '';

function loadFiles()
{
        var input = $('fileInput');
        for (var i = 0; i < input.files.length; i++) 
        {
            var f = input.files[i];

            var reader = new FileReader();
            reader.readAsBinaryString(f);

            reader.onload = function(e){

                var fbinary = e.target.result;
                var fsize = f.size;

                var url = 'https://www.googleapis.com/upload/storage/v1beta2/b/<mybucket>/o?';
                url += 'uploadType=media&name='+f.name+ ' HTTP/1.1';

                var req = boundary + 
                '\r\nContent-Type: application/http'+
                '\r\nContent-Transfer-Encoding: binary'+
                '\r\n\nPOST ' + url +
                '\r\nContent-Type: image/jpeg'+
                '\r\nContent-Length: '+ f.size +
                '\r\nAuthorization: '+tok+
                '\r\n\n'+ fbinary + '\n';

                consolidated_request += req;
            };

        }
}

当用户点击上传时:

$('upload').onclick = function(e){

    var xhr = new XMLHttpRequest();
    xhr.open("POST", 'https://www.googleapis.com/batch', true);
    xhr.setRequestHeader("Authorization", tok);
    xhr.setRequestHeader("Content-Type", "multipart/mixed;boundary=" + boundary);
    xhr.send(consolidated_request);
 };

这是生成的 POST 示例(使用 firebug):

标题:

Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Authorization   Bearer ya29.AHES6ZQgu6gFurD6y7Bo2Mao1RNCFwyqNZcwvgDZ82RXIbQ4
Content-Length  159866
Content-Type    multipart/mixed; charset=UTF-8;boundary=---======= foo_bar_baz12034245623562346 ===
Host    www.googleapis.com

身体:

 --======= foo_bar_baz12034245623562346 === 
Content-Type: application/http 
Content-Transfer-Encoding: binary 

POST https://www.googleapis.com/upload/storage/v1beta2/b/<mybucket>/o?uploadType=media&name=myimage.jpg HTTP/1.1 
Content-Type: image/jpeg 
Content-Length: 69436 
Authorization: Bearer ya29.AHES6ZQgu6gFurD6y7Bo2Mao1RNCFwyqNZcwvgDZ82RXIbQ4 

ÿØÿà�JFIF���d�d��ÿì�Ducky�����&lt;��ÿî�Adobe�dÀ���ÿÛ�� 
...

问题是没有响应,因为我收到 400 bad request msg。这个请求有什么问题?

4

1 回答 1

1
于 2013-09-18T05:18:50.560 回答