More downloading files via JS and XPCOM issues

Adam Fletcher <[email protected]> Wed, 13 Nov 2002 11:34:52 -0500
Newsgroups gmane.comp.mozilla.devel.xpcom
Organization Another Netscape Collabra Server User
Message-ID <[email protected]>
Hello,

I've written some Javascript code that uses XPCOM to allow a user to 
download a file to there local disk. The problem is that this code only 
works for ASCII files (maybe just 7-bit?), not binary. Binary files come 
out corrupt. Does anyone know what I might be doing wrong?

---

var oURL = createInstance('@mozilla.org/network/standard-url;1',
                 'nsIURL');
oURL.spec = "http://www.example.com/somebinaryfile.doc";


var ioServiceForDownload = 
getService('@mozilla.org/network/io-service;1',
                             'nsIIOService');

var downloadChann = 
ioServiceForDownload.newChannelFromURI(oURL).QueryInterface( 
                             Components.interfaces.nsIHttpChannel);


var fp = downloadDocumentToDisk(title);


var fileOutputStream = createInstance("@mozilla.org/network/file-out
put-stream;1", "nsIFileOutputStream");

if(!fp) { return; }
fp.create(fp.NORMAL_FILE_TYPE, 0600);

fileOutputStream.init(fp, 2, 0600, false);

downloadChann.asyncOpen(saveFileListener, fileOutputStream);


var saveFileListener  = {
     onDataAvailable: function (channel, ctxt, inStr, sourceOffset,
                                 count) {

         var scriptableStream = toScriptableStream(inStr);
         var theData = scriptableStream.read(count);
         ctxt.write(theData, count);
         return;
     },
     onStartRequest: function (channel, ctxt) {
         consolePrint("onStartRequest, status: " + channel.status, true);
         return;
     },
     onStopRequest: function (channel, ctxt, status) {
         consolePrint("onStopRequest, status: " + status, true);
         ctxt.close();
         return;
     }

};


function downloadDocumentToDisk(fileName)
{
     var nsIFilePicker = Components.interfaces.nsIFilePicker;
     var fp = Components.classes["@mozilla.org/filepicker;1"]
             .createInstance(nsIFilePicker);
     fp.init(top, "Save As", nsIFilePicker.modeSave);
     fp.defaultString = fileName;
     var rv = fp.show();
     if(rv == nsIFilePicker.returnCancel) { return null; }

     return fp.file;
}


function toScriptableStream(input) {
     var SIStream = Components.Constructor(
         '@mozilla.org/scriptableinputstream;1',
         'nsIScriptableInputStream', 'init');
     return new SIStream(input);
}