Загрузите файл BIM360 Docs, используя Javascript
Я пытаюсь загрузить файлы документов BIM360 с помощью JavaScript. Я могу получить ответ от файла 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)
}
});
});
1 ответ
Чтобы загрузить файлы из службы BIM360, я использовал пользовательские транспорты jjuj Ajax для создания нового XMLHttpRequest и передачи всех полученных данных обратно в jQuery, см. Здесь подробную информацию о транспортах Ajax с jQuery.
/**
*
* 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();
}
};
}
});
Следующий фрагмент кода - это код, который я использовал для загрузки файла из корзины BIM360 через API управления данными Forge. С помощью вышеупомянутых пользовательских Ajax-транспортов и dataType: 'binary'
ответ API будет обрабатываться как блоб. После этого нам просто нужно создать URL-адрес BLOB-объекта и временную ссылку HTML, чтобы открыть URL-адрес BLOB-объекта для сохранения загруженного файла.
Чтобы получить фактический URL-адрес хранилища файлов, вы должны вызвать API GET Item Versions, а ссылка на скачивание является значением storage.meta.link.href
атрибут каждой версии данных элемента в ответе API.
$(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);
});
});
})
Надеюсь, поможет.