2013-02-11 16 views
7

Tôi đang bắt đầu ứng dụng GTK javascript đầu tiên của mình và tôi muốn tải xuống tệp và theo dõi tiến trình của nó bằng Gtk.ProgressBar. Các tài liệu duy nhất mà tôi có thể tìm thấy về các yêu cầu http là một số ví dụ mã ở đây:Sử dụng gjs, làm cách nào bạn có thể thực hiện yêu cầu http không đồng bộ để tải xuống tệp theo khối?

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

Và một số tài liệu tham khảo Súp khó hiểu ở đây:

http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Soup.SessionAsync.html

Từ những gì tôi có thể thu thập, tôi có thể làm điều gì đó như thế này:

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

Chỉ có vẻ là một cuộc gọi lại khi quá trình tải xuống hoàn tất và tôi không thể tìm bất kỳ cách nào để đặt chức năng gọi lại cho bất kỳ sự kiện dữ liệu nào. Tôi có thể làm cái này như thế nào?

Đây là thực sự dễ dàng trong 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(); 

Trả lời

4

Nhờ giúp đỡ từ [email protected], tôi đã figured it out. Nó chỉ ra Soup.Message có các sự kiện mà bạn có thể liên kết với, bao gồm một cái gọi là got_chunk và một cái gọi là 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'); 
}); 
Các vấn đề liên quan