Downloading Files

Downloading files

To download a file, create an instance of nsIWebBrowserPersist and call its nsIWebBrowserPersist.saveURI() method, passing it a URL to download and an nsIFile instance representing the local file name/path. 

01 // create a persist
02 var persist = Components.classes[ "@mozilla.org/embedding/browser/nsWebBrowserPersist;1" ]
03                .createInstance(Components.interfaces.nsIWebBrowserPersist);
04  
05 // with persist flags if desired See nsIWebBrowserPersist page for more PERSIST_FLAGS.
06 const nsIWBP = Components.interfaces.nsIWebBrowserPersist;
07 const flags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
08 persist.persistFlags = flags | nsIWBP.PERSIST_FLAGS_FROM_CACHE;
09  
10 // do the save
11 persist.saveURI(uriToFile, null , null , null , "" , nsIFile);

If you don't need detailed progress information, you might be happier with nsIDownloader .

Downloading Binary Files with a Progress Listener

To download a binary file with custom progress listener:

01 var persist = Components.classes[ "@mozilla.org/embedding/browser/nsWebBrowserPersist;1" ]
02                .createInstance(Components.interfaces.nsIWebBrowserPersist);
03 var file = Components.classes[ "@mozilla.org/file/local;1" ]
04             .createInstance(Components.interfaces.nsILocalFile);
05 file.initWithPath( "C://a//path//file.bin" ); // download destination
06 var obj_URI = Components.classes[ "@mozilla.org/network/io-service;1" ]
07                .getService(Components.interfaces.nsIIOService)
08                .newURI(aURLToDownload, null , null );
09 persist.progressListener = {
10    onProgressChange: function (aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {
11      var percentComplete = (aCurTotalProgress/aMaxTotalProgress)*100;
12      var ele = document.getElementById( "progress_element" );
13      ele.innerHTML = percentComplete + "%" ;
14    },
15    onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus) {
16      // do something
17    }
18 }
19 persist.saveURI(obj_URI, null , null , null , "" , file);
Downloading files that require credentials

Before calling nsIWebBrowserPersist.saveURI() , you need to set the progressListener property of the nsIWebBrowserPersist instance to an object that implements nsIAuthPrompt . Normally, nsIAuthPrompt expects a prompt to be displayed so the user can enter credentials, but you can return a username and password credentials directly without prompting the user. If you want to open a login prompt, you can use the default prompt by calling the window watcher's getNewAuthPrompter() method.

01 var persist = Components.classes[ "@mozilla.org/embedding/browser/nsWebBrowserPersist;1" ]
02                .createInstance(Components.interfaces.nsIWebBrowserPersist);
03 var hardCodedUserName = "ericjung" ;
04 var hardCodedPassword = "foobar" ;
05 persist.progressListener = {
06  
07    QueryInterface: function (iid) {
08       if (iid.equals(Components.interfaces.nsIAuthPrompt) ||
09           iid.equals(Components.interfaces.nsISupports))
10         return this ;
11       throw Components.results.NS_ERROR_NO_INTERFACE;
12    },
13  
14    // implements nsIAuthPrompt
15    prompt: function (dialogTitle, text, passwordRealm, savePassword, defaultText, result) {
16      result.value = hardCodedPassword;
17      return true ;
18    },
19    promptPassword: function (dialogTitle, text, passwordRealm, savePassword, pwd) {
20      pwd.value = hardCodedPassword;
21      return true ;
22    },
23    promptUsernameAndPassword: function (dialogTitle, text, passwordRealm, savePassword, user, pwd) {
24      user.value = hardCodedUserName;
25      pwd.value = hardCodedPassword;   
26      return true ;
27    }
28 };
29 persist.saveURI(urlToFile, null , null , null , "" , nsFileInstance);

The above is going to give you errors about missing nsIDownloadProgressListener methods, so you should implement that as well. For example, with empty dummy methods if you are not interested about the progress.

Instead of using QI like above, you can also implement nsIInterfaceRequestor and return nsIAuthPrompt from there, like nsIWebBrowserPersist .progressListener documentation suggests.

Downloading Images

Sample function for fetching an image file from a URL.

01 // This function is for fetching an image file from a URL.
02 // Accepts a URL and returns the file.
03 // Returns empty if the file is not found (with an 404 error for instance).
04 // Tried with .jpg, .ico, .gif (even .html).
05  
06 function GetImageFromURL(url) {
07    var ioserv = Components.classes[ "@mozilla.org/network/io-service;1" ]
08                 .getService(Components.interfaces.nsIIOService);
09    var channel = ioserv.newChannel(url, 0, null );
10    var stream = channel.open();
11  
12    if (channel instanceof Components.interfaces.nsIHttpChannel && channel.responseStatus != 200) {
13      return "" ;
14    }
15  
16    var bstream = Components.classes[ "@mozilla.org/binaryinputstream;1" ]
17                  .createInstance(Components.interfaces.nsIBinaryInputStream);
18    bstream.setInputStream(stream);
19  
20    var size = 0;
21    var file_data = "" ;
22    while (size = bstream.available()) {
23      file_data += bstream.readBytes(size);
24    }
25  
26    return file_data;
27 }

Download observers

Sample download observer for Firefox 2 Download manager.

01 // ******************************
02 // DownloadObserver
03 // ******************************
04 function sampleDownload_init(){
05    //**** Add download observer
06    var observerService = Components.classes[ "@mozilla.org/observer-service;1" ]
07                          .getService(Components.interfaces.nsIObserverService);
08    observerService.addObserver(sampleDownloadObserver, "dl-start" , false );
09    observerService.addObserver(sampleDownloadObserver, "dl-done" , false );
10    observerService.addObserver(sampleDownloadObserver, "dl-cancel" , false );
11    observerService.addObserver(sampleDownloadObserver, "dl-failed" , false );
12  
13    window.addEventListener( "unload" , function () {
14      observerService.removeObserver(sampleDownloadObserver, "dl-start" );
15      observerService.removeObserver(sampleDownloadObserver, "dl-done" );
16      observerService.removeObserver(sampleDownloadObserver, "dl-cancel" );
17      observerService.removeObserver(sampleDownloadObserver, "dl-failed" );
18    }, false );
19 }
20 var sampleDownloadObserver = {
21    observe: function (subject, topic, state) {
22      var oDownload = subject.QueryInterface(Components.interfaces.nsIDownload);
23      //**** Get Download file object
24      var oFile = null ;
25      try {
26        oFile = oDownload.targetFile;  // New firefox 0.9+
27      } catch (e){
28        oFile = oDownload.target;      // Old firefox 0.8
29      }
30      //**** Download Start
31      if (topic == "dl-start" ){
32        alert( 'Start download to - ' +oFile.path);
33      }
34      //**** Download Cancel
35      if (topic == "dl-cancel" ){
36        alert( 'Canceled download to - ' +oFile.path);
37      }
38      //**** Download Failed
39      else if (topic == "dl-failed" ){
40        alert( 'Failed download to - ' +oFile.path);
41      }
42      //**** Download Successs
43      else if (topic == "dl-done" ){
44        alert( 'Done download to - ' +oFile.path);
45      }   
46    }
47 }
48 window.addEventListener( "load" , sampleDownload_init, false );
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值