2013-02-11 82 views
7

我開始使用我的第一個JavaScript GTK應用程序,我想下載一個文件並使用Gtk.ProgressBar跟蹤它的進度。唯一的文檔,我可以找到關於HTTP請求是一些示例代碼在這裏:這裏使用gjs,如何使異步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(); 

回答

4

由於從[email protected]幫助,我已經想通了。事實證明,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'); 
});