簡體   English   中英

使用Javascript下載BIM360 Docs文件

[英]Download BIM360 Docs file using Javascript

我正在嘗試使用JavaScript下載BIM360文檔文件。 我能夠從BIM360獲得文件響應,但無法保存具有適當內容的文件。 這是我的JS代碼-

$(document).ready(function () {
    var anchor = $('.vcard-hyperlink');
    $.ajax({
        url: <file downloaded URL>,
        type: "GET",
        headers: {
            "Authorization": "Bearer " + <accessToken>
        },
        beforeSend: function (jqxhr) {

        },
        success: function (data) {
            // create a blob url representing the data
            var blob = new Blob([data]);
            var url = window.URL.createObjectURL(blob);
            // attach blob url to anchor element with download attribute
            var anchor = document.createElement('a');
            anchor.setAttribute('href', url);
            anchor.setAttribute('download', "test.docx");
            anchor.click();
            window.URL.revokeObjectURL(url);

        },
        error: function (jqxhr, textStatus, errorThrown) {
            console.log(textStatus, errorThrown)
        }
    });
});

為了從BIM360服務下載文件,我使用了jQuery的自定義Ajax傳輸來創建新的XMLHttpRequest並將所有接收到的數據傳遞回jQuery,請參閱此處以獲取有關jQuery的Ajax傳輸的詳細信息。

/**
 *
 * jquery.binarytransport.js
 *
 * @description. jQuery ajax transport for making binary data type requests.
 * @version 1.0 
 * @author Henry Algus <henryalgus@gmail.com>
 *
 */
// use this transport for "binary" data type
$.ajaxTransport("+binary", function(options, originalOptions, jqXHR) {
    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) {
        return {
            // create new XMLHttpRequest
            send: function(headers, callback) {
                // setup all variables
                var xhr = new XMLHttpRequest(),
                    url = options.url,
                    type = options.type,
                    async = options.async || true,
                    // blob or arraybuffer. Default is blob
                    dataType = options.responseType || "blob",
                    data = options.data || null,
                    username = options.username || null,
                    password = options.password || null;

                xhr.addEventListener('load', function() {
                    var data = {};
                    data[options.dataType] = xhr.response;
                    // make callback and send data
                    callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                });

                xhr.open(type, url, async, username, password);

                // setup custom headers
                for (var i in headers) {
                    xhr.setRequestHeader(i, headers[i]);
                }

                xhr.responseType = dataType;
                xhr.send(data);
            },
            abort: function() {
                jqXHR.abort();
            }
        };
    }
});

以下代碼段是我用於通過Forge數據管理API從BIM360存儲桶下載文件的代碼。 使用上面的自定義Ajax傳輸和dataType: 'binary' ,API響應將作為blob處理。 之后,我們只需要創建一個Blob URL和一個臨時HTML鏈接即可打開Blob URL,以保存下載的文件。

要獲取實際的文件存儲URL,必須調用API GET Item Versions ,並且下載鏈接是API響應中每個項目版本數據的storage.meta.link.href屬性的值。

$(function() {

  $('a#download').click(function(event) {
    event.preventDefault();

    const filename = '2f536896-88c8-4dee-b0c1-cdeee231a028.zip';

    const settings = {
      crossDomain: true,
      url: 'https://developer.api.autodesk.com/oss/v2/buckets/wip.dm.prod/objects/' + filename,
      method: 'GET',
      dataType: 'binary',
      processData: false,
      headers: {
        Authorization: 'Bearer YOUR_ACCESS_TOKEN',
        Content-Type: 'application/octet-stream'
      }
    };

    $.ajax(settings).done(function (blob, textStatus, jqXHR) {
        console.log(blob );
        console.log(textStatus);

      if( navigator.msSaveBlob )
        return navigator.msSaveBlob(blob, filename);

      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.style = 'display: none';
      document.body.appendChild(a);

      a.href = url;
      a.download = filename;
      a.click();
      URL.revokeObjectURL(url);
    });
  });
})

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM