使用gjs,如何进行异步http请求,以分块下载文件
Using gjs, how can you make an async http request to download a file in chunks?
我正在启动我的第一个javascript GTK应用程序,我想下载一个文件并用GTK.ProgressBar跟踪它的进度。我能找到的关于http请求的唯一文档是这里的一些示例代码:
http://developer.gnome.org/gnome-devel-demos/unstable/weatherGeonames.js.html.en
这里有一些令人困惑的汤参考:
http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Soup.SessionAsync.html
据我所知,我可以做这样的事情:
const Soup = imports.gi.Soup;
var _httpSession = new Soup.SessionAsync();
Soup.Session.prototype.add_feature.call(_httpSession, new Soup.ProxyResolverDefault());
var request = Soup.Message.new('GET', url);
_httpSession.queue_message(request, function(_httpSession, message) {
print('download is done');
}
下载完成后似乎只有一个回调,我找不到任何方法为任何数据事件设置回调函数。我该怎么做?
这在node.js:中非常容易
var req = http.request(url, function(res){
console.log('download starting');
res.on('data', function(chunk) {
console.log('got a chunk of '+chunk.length+' bytes');
});
});
req.end();
感谢javascript-list@gnome.org,我想明白了。事实证明,Soup.Message有一些事件可以绑定,其中包括一个名为got_chunk的事件和一个称为got_headers的事件。
const Soup = imports.gi.Soup;
const Lang = imports.lang;
var _httpSession = new Soup.SessionAsync();
Soup.Session.prototype.add_feature.call(_httpSession, new Soup.ProxyResolverDefault());
// variables for the progress bar
var total_size;
var bytes_so_far = 0;
// create an http message
var request = Soup.Message.new('GET', url);
// got_headers event
request.connect('got_headers', Lang.bind(this, function(message){
total_size = message.response_headers.get_content_length()
}));
// got_chunk event
request.connect('got_chunk', Lang.bind(this, function(message, chunk){
bytes_so_far += chunk.length;
if(total_size) {
let fraction = bytes_so_far / total_size;
let percent = Math.floor(fraction * 100);
print("Download "+percent+"% done ("+bytes_so_far+" / "+total_size+" bytes)");
}
}));
// queue the http request
_httpSession.queue_message(request, function(_httpSession, message) {
print('Download is done');
});
相关文章:
- 如何在生成下载文件时显示加载动画
- 直接下载文件,而不是从window.open(url)
- Javascript运行php文件,然后下载文件
- 在单击href链接的同时下载文件
- 通过javascript下载文件时设置文件名
- HTML锚标记无法在android平台中下载文件
- 链接/按钮从子文件夹下载文件--浏览器只是浏览
- iPhone强制下载文件
- 正在下载文件,同时加载另一个页面
- 如何在node.js中只下载文件的前10 KB
- 如何使用XMLHttpRequest下载文件
- 使用angular js在前端下载文件
- 使用blob从ajax结果下载文件
- 通过Android Chrome浏览器下载文件
- 使用AJAX下载文件.来自SD卡
- 如何使用phonegap从android中的URL下载文件
- 使用ajax下载文件
- 无法使用Angular JS和spring MVC打开下载文件
- 无法使用API-node.js从Google Drive下载文件
- 点击jQuery按钮下载文件