使用 Javascript 下载 BIM360 Docs 文件

2024-05-07

我正在尝试使用 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 服务下载文件,我使用了自定义Ajax 传输 http://api.jquery.com/jquery.ajaxtransport/jQuery 创建新的 XMLHttpRequest 并将所有接收到的数据传递回 jQuery,请参阅here http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/有关使用 jQuery 进行 Ajax 传输的详细信息。

/**
 *
 * jquery.binarytransport.js
 *
 * @description. jQuery ajax transport for making binary data type requests.
 * @version 1.0 
 * @author Henry Algus <[email protected] /cdn-cgi/l/email-protection>
 *
 */
// 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获取项目版本 https://developer.autodesk.com/en/docs/data/v2/reference/http/projects-project_id-items-item_id-versions-GET/,下载链接的值为storage.meta.link.hrefAPI 响应中每个项目版本数据的属性。

$(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);
    });
  });
})

希望能帮助到你。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Javascript 下载 BIM360 Docs 文件 的相关文章

随机推荐