是二进制文件(pdf,word,excel,ppt,mp3,...)可以使用XHR或fetch下载? [英] is binary file(pdf, word, excel, ppt, mp3,...) download possible using XHR or fetch?
问题描述
是可以使用XHR或fetch下载的二进制文件(pdf,word,excel,ppt,mp3,...)我看到了使用数据URI和base64转换的pdf和图像的一些片段和技巧。我们有更好的机制吗?
is binary file(pdf, word, excel, ppt, mp3,...) download possible using XHR or fetch? I have seen some snippets and tricks for pdf and images using data URI and base64 conversion. Do we have some better mechanism available?
我需要下载具有以下限制的文件:
I need to download a file with following constraints:
- 文件下载请求必须使用oauth2令牌进行身份验证。基本上这意味着我需要将Authorization标题设置为某个值。
- 服务器返回分块数据。需要加入块(或者我可以强制服务器发送非分块数据)
我的NodeJS代码
获取元数据
var options = {
hostname : API_HOST ,
method : 'GET',
port : 443,
path : API_PATH + fileId,
headers : {
'Authorization' : 'Bearer ' + GOOGLE_ACCESS_TOKEN
}
}
var meta = '';
var fileRequest = https.request(options, function(response) {
response.setEncoding('utf8');
response.on('data', function(chunk) {
meta += chunk;
});
response.on('end', function(error) {
callback(error, meta);
})
});
获取实际文件
var file = fs.createWriteStream(GDRIVE_ROOT + '\\' + JSON.parse(meta).originalFilename);
var options = {
hostname : url.parse(JSON.parse(meta).downloadUrl).hostname,
method : 'GET',
port : 443,
path : url.parse(JSON.parse(meta).downloadUrl).path,
headers : {
'Authorization' : 'Bearer ' + GOOGLE_ACCESS_TOKEN
}
}
var request = https.request(options, function(response) {
response.pipe(file);
});
request.end();
我已经为NodeJS工作了。有没有办法让我在浏览器中实现文件下载。我在 http://jsfiddle.net/LdyruLwv/ 中提供了一个非工作的代码, p>
I have it working for NodeJS. Is there a way for me to achieve the file download in browser. I have a non-working piece of code using fetch at http://jsfiddle.net/LdyruLwv/
推荐答案
传输编码对浏览器中的应用程序应该是透明的,不要担心。
以下是一个基本的ajax文件下载解决方案,它使用XHR2,blob和具有下载属性的锚点。
The transfer encoding should be transparent to an application in a browser, don't worry about it.
Below is a basic ajax file download solution, it uses XHR2, blobs and anchors with download properties.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
var blobURL = window.URL.createObjectURL(this.response);
var anchor = document.createElement('a');
anchor.download = 'filename.ext';
anchor.href = blobUrl;
anchor.click();
}
}
xhr.open('GET', request_url);
xhr.setRequestHeader('Authorization', 'Bearer ' + GOOGLE_ACCESS_TOKEN);
xhr.responseType = 'blob'; // Get a binary response
xhr.send(jData);
这篇关于是二进制文件(pdf,word,excel,ppt,mp3,...)可以使用XHR或fetch下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!