`

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 );
分享到:
评论

相关推荐

    Downloading files to a PhoneGap application

    《使用PhoneGap应用程序下载文件》 ...这个主题的核心是探讨如何在PhoneGap应用中实现文件下载功能,这对于创建需要离线存储数据或更新内容的应用至关重要。 在Part 1中,我们首先会了解PhoneGap的基础知识,包括其...

    Uploading and Downloading Files in Web Dynpro Java

    ### SAP NetWeaver 04 Web Dynpro Java:文件上传与下载 #### 一、概述 在企业级应用开发中,文件的上传与下载是非常常见的功能需求之一。特别是在使用SAP NetWeaver 04平台进行开发时,利用Web Dynpro Java框架...

    aria2 win64位版本

    下载工具,aria2 is a utility for downloading files. The supported protocols are HTTP(S), FTP, SFTP, BitTorrent, and Metalink. aria2 can download a file from multiple sources/protocols and tries to ...

    数据分析视频--Getting and Cleaning Data.zip

    1 - 4 - Downloading Files (7-09).mp4 1 - 5 - Reading Local Files (4-55).mp4 1 - 6 - Reading Excel Files (3-55).mp4 1 - 7 - Reading XML (12-39).mp4 1 - 8 - Reading JSON (5-03).mp4 1 - 9 - The data....

    HTTPGET-单线程下载(源代码)

    file name: httpget.zipreplacements: file version: 1.94file description: The HTTPGet component intended for downloading files/documents/results of CGI scripts from the web using standard Microsoft ...

    Visual C++ 编程资源大全(英文源码 网络)

    demo.zip How to open a new dialup connection using RasDial(10KB)<END><br>16,webgrab.zip A simple class to ease the task of downloading files from the net(25KB)<END><br>17,multicastsocket.zip ...

    ftp_server.zip_FTP server client_PocketOBEX_bluetooth_bluetooth

    * Downloading files Since the filesystem is read only, folder listings can be pre-generated using the included make_listing.pl Perl script for each folder. Each folder to be included in the FTP ...

    Catalyst socket tools v6

    Using SocketTools, you can easily add features such as uploading and downloading files, sending and retrieving e-mail, exchanging information with web servers, interactive terminal sessions and ...

    Aria2135032bit.7z

    aria2 is a utility for downloading files. The supported protocols are HTTP(S), FTP, SFTP, BitTorrent, and Metalink. aria2 can download a file from multiple sources/protocols and tries to utilize your ...

    linuxdeploy-2.1.0-237.apk

    Installation of a distribution is done by downloading files from official mirrors online over the internet. The application can run better with superuser rights (root). The program supports multi ...

    firefox-document

    2. "Downloading Files - Mozilla _ MDN.htm":这个文件很可能详细介绍了Firefox的下载功能和最佳实践。MDN通常会提供关于如何安全地下载文件、配置下载设置、处理下载问题以及理解相关安全警告的指导。 通过这两个...

    Professional C# 3rd Edition

    Internal Comments Within the Source Files 67 XML Documentation 68 The C# Preprocessor Directives 70 #define and #undef 70 #if, #elif, #else, and #endif 71 #warning and #error 72 #region and #endregion...

    Ubuntu The Complete Reference

    - **FTP Clients**: Discussion of FTP clients for uploading and downloading files over the internet. - **Java Clients**: Brief introduction to Java-based applications and how they can be installed and ...

    VB编程资源大全(英文控件)

    PicOpener.zip PicOpener is an ActiveX control that allows you to read image files in over 50 formats and convert them to BMP bitmaps<END><br>20,PicConverter.zip Read over 50 and write 15 image ...

    Linux高级bash编程

    Converting DOS Batch Files to Shell Scripts M. Exercises M.1. Analyzing Scripts M.2. Writing Scripts N. Revision History O. Mirror Sites P. To Do List Q. Copyright 表格清单: 11-1. 作业标识符 30...

    Advanced Bash-Scripting Guide <>

    Converting DOS Batch Files to Shell Scripts M. Exercises M.1. Analyzing Scripts M.2. Writing Scripts N. Revision History O. Mirror Sites P. To Do List Q. Copyright 表格清单: 11-1. 作业标识符 30-1. ...

    应用Dephi 开发佳能照相机API

    {****************************************************************************** * * * PROJECT : EOS Digital Software Development Kit EDSDK * * NAME : EDSDKApi.pas * * * * Description: This is the ...

    STM32CubeMX软件库文件安装(STM32Cube_FW_F4_V1.23.0)Part4

    STM32CubeMX软件f4系列2019年4月最新cube库文件STM32Cube_FW_F4_V1.23.0,由于附件大小限制,文件分成4个压缩包,请全部下载后放到同一个文件夹下解压

Global site tag (gtag.js) - Google Analytics