2013-02-11 12 views
7

İlk javascript GTK uygulamasına başlıyorum ve bir dosya indirmek ve Gtk.ProgressBar ile ilerlemesini izlemek istiyorum. BuradaJS'leri kullanarak, bir dosyayı toplu olarak indirmek için bir async http isteği nasıl yapabilirsiniz?

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

Ve bazı kafa karıştırıcı Çorba referans:

Ben anladığımıza http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Soup.SessionAsync.html

, bir şey yapabileceğini http istekleri hakkında bulabilirsiniz Yalnızca doküman bazı örnek burada kodudur şunun gibi:

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

Yalnızca indirme işlemi tamamlandığında bir geri arama var gibi görünüyor ve yapamıyorum Herhangi bir veri olayı için geri arama işlevi ayarlamanın herhangi bir yolunu bulmak. Bunu nasıl yapabilirim?

Bu node.js gerçekten kolaydır:

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(); 

cevap

4

Teşekkür [email protected] dan yardım etmek, bunu anladım. Soup.Message, got_chunk ve bir tane got_headers denen biri de dahil olmak üzere, bağlayabileceğiniz etkinliklere sahip.

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