Code snippets:Downloading Files
From MDC
Contents |
[edit] Downloading Files
To download a file, create an instance of nsIWebBrowserPersist and call its saveURI() method, passing it a URL to download and an nsIFile instance representing the local file name/path.
var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].
createInstance(Components.interfaces.nsIWebBrowserPersist);
persist.saveURI(urlToFile, null, null, null, "", nsFileInstance);
[edit] 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.
TODO: This code needs testing
var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].
createInstance(Components.interfaces.nsIWebBrowserPersist);
var hardCodedUserName = "ericjung";
var hardCodedPassword = "foobar";
persist.progressListener = {
// implements nsIAuthPrompt
prompt: function(dialogTitle, text, passwordRealm, savePassword, defaultText, result) {
result.value = hardCodedPassword;
return true;
},
promptPassword: function(dialogTitle, text, passwordRealm, savePassword, pwd) {
pwd.value = hardCodedPassword;
return true;
},
promptUsernameAndPassword: function(dialogTitle, text, passwordRealm, savePassword, user, pwd) {
user.value = hardCodedUserName;
pwd.value = hardCodedPassword;
return true;
}
};
persist.saveURI(urlToFile, null, null, null, "", nsFileInstance);
[edit] Downloading Images
Sample function for fetching an image file from a URL.
// This function is for fetching an image file from a URL.
// Accepts a URL and returns the file.
// Returns empty if the file is not found (with an 404 error for instance).
// Tried with .jpg, .ico, .gif (even .html).
function GetImageFromURL(url) {
var ioserv = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var channel = ioserv.newChannel(url, 0, null);
var stream = channel.open();
if (channel instanceof Components.interfaces.nsIHttpChannel && channel.responseStatus != 200) {
return "";
}
var bstream = Components.classes["@mozilla.org/binaryinputstream;1"]
.createInstance(Components.interfaces.nsIBinaryInputStream);
bstream.setInputStream(stream);
var size = 0;
var file_data = "";
while(size = bstream.available()) {
file_data += bstream.readBytes(size);
}
return file_data;
}
[edit] Download Observers
Sample download observer for Firefox 2 Download manager.
// ******************************
// DownloadObserver
// ******************************
function sampleDownload_init(){
//**** Add download observer
var observerService = Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(sampleDownloadObserver, "dl-start", false);
observerService.addObserver(sampleDownloadObserver, "dl-done", false);
observerService.addObserver(sampleDownloadObserver, "dl-cancel", false);
observerService.addObserver(sampleDownloadObserver, "dl-failed", false);
window.addEventListener("unload", function() {
observerService.removeObserver(sampleDownloadObserver, "dl-start");
observerService.removeObserver(sampleDownloadObserver, "dl-done");
observerService.removeObserver(sampleDownloadObserver, "dl-cancel");
observerService.removeObserver(sampleDownloadObserver, "dl-failed");
}, false);
}
var sampleDownloadObserver = {
observe: function (subject, topic, state) {
var oDownload = subject.QueryInterface(Components.interfaces.nsIDownload);
//**** Get Download file object
var oFile = null;
try{
oFile = oDownload.targetFile; // New firefox 0.9+
} catch (e){
oFile = oDownload.target; // Old firefox 0.8
}
//**** Download Start
if (topic == "dl-start"){
alert('Start download to - '+oFile.path);
}
//**** Download Cancel
if(topic == "dl-cancel"){
alert('Canceled download to - '+oFile.path);
}
//**** Download Failed
else if(topic == "dl-failed"){
alert('Failed download to - '+oFile.path);
}
//**** Download Successs
else if(topic == "dl-done"){
alert('Done download to - '+oFile.path);
}
}
}
window.addEventListener("load", sampleDownload_init, false);