通过js跟踪文件上传到谷歌云存储的进度? [英] Track progress of file upload to google cloud storage via js?

查看:164
本文介绍了通过js跟踪文件上传到谷歌云存储的进度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在使用javascript客户端时是否可以跟踪文件上传到谷歌云存储的进度?由于我有一个进度条,我想向用户显示目前已上传了多少文件。

I'm wondering if it is possible to track the progress of a file upload to google cloud storage when using the javascript client? As I have a progress bar that I would like to show to the user on how much of the file has been uploaded so far.

我正在使用相同的上传代码谷歌提供他们的示例页面用于文件上传。

I'm using the same upload code that google gives on their example page for file upload.

推荐答案

而不是使用 gapi.client.request 由js库提供的api我创建了一个 XMLHttpRequest ,并为事件 progress 附加了一个事件监听器。如下所示:

Instead of using the gapi.client.request api provided by the js library I instead created an XMLHttpRequest and appended a event listener for the event progress. As seen by the following:

      const boundary = '-------314159265358979323846';
      const delimiter = "\r\n--" + boundary + "\r\n";
      const close_delim = "\r\n--" + boundary + "--";

      var reader = new FileReader();
      reader.readAsBinaryString(fileData);
      reader.onload = function(e) {
        var contentType = fileData.type || 'application/octet-stream';
        var metadata = {
          'name': 'testing',
          'mimeType': contentType
        };

        var base64Data = btoa(reader.result);
        var multipartRequestBody =
          delimiter +
          'Content-Type: application/json\r\n\r\n' +
          JSON.stringify(metadata) +
          delimiter +
          'Content-Type: ' + contentType + '\r\n' +
          'Content-Transfer-Encoding: base64\r\n' +
          '\r\n' +
          base64Data +
          close_delim;

        gapi.client.request()
        var xhr = new XMLHttpRequest();

        xhr.open('POST', 'https://www.googleapis.com/upload/storage/v1/b/bucket/o?uploadType=multipart&key=apiKey&alt=json', true);

        xhr.setRequestHeader('Content-Type', 'multipart/mixed; boundary="' + boundary + '"');
        xhr.setRequestHeader('authorization', 'Bearer ' + gapi.auth.getToken().access_token);

        xhr.upload.addEventListener("progress", function(e) {
          var pc = parseFloat(e.loaded / e.total * 100).toFixed(2);
        }, false);

        xhr.onreadystatechange = function(e) {
          if (xhr.readyState == 4) {
            console.log(xhr.responseText);
          }
        };

        xhr.send(multipartRequestBody);

归因:大部分代码都来自Google的js库,只有另外还有用于收听上传进度的事件监听器。

Attribution: Majority of code was taken from Google's js library with the only addition being the event listener for listening to the progress of the upload.

这篇关于通过js跟踪文件上传到谷歌云存储的进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆