【问题标题】:Using gjs, how can you make an async http request to download a file in chunks?使用 gjs,如何发出异步 http 请求以分块下载文件?
【发布时间】:2013-02-12 03:38:21
【问题描述】:

我开始使用我的第一个 javascript GTK 应用程序,我想下载一个文件并使用 Gtk.ProgressBar 跟踪它的进度。我能找到的关于 http 请求的唯一文档是这里的一些示例代码:

http://developer.gnome.org/gnome-devel-demos/unstable/weatherGeonames.js.html.en

还有一些令人困惑的 Soup 参考:

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 gtk gjs


    【解决方案1】:

    感谢 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');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 2011-01-08
      • 2016-11-15
      相关资源
      最近更新 更多