[英]How to Asynchronously write an ArrayBuffer directly to file using nsIArrayBufferInputStream in Firefox extension
簡而言之:如何在Firefox擴展中使用nsIArrayBufferInputStream將ArrayBuffer直接異步寫入文件? 似乎MDN在nsIArrayBufferInputStream上沒有任何文檔。
我知道我可以使用nsIStringInputStream並將BufferArray轉換為String,但這也對使用以下代碼將ArrayBuffer轉換為String造成了很大的影響:
String.fromCharCode.apply(null, new Uint16Array(buf));
如果緩沖區大於或等於500 KB則不起作用,因此我們必須一次循環一個字符:
for (let i = 0; i < buf.length; i++){
s += String.fromCharCode(buf16[i]);
}
或者,我可以使用nsIBinaryOutputStream.writeByteArray,但不能與NetUtil.asyncCopy一起使用(或者可以嗎?)
//this works ok, but is synchronous :-(
function writeBinFile(aFile, data){
Components.utils.import("resource://gre/modules/FileUtils.jsm");
let nsFile = Components.Constructor("@mozilla.org/file/local;1", Ci.nsILocalFile, "initWithPath");
if(typeof aFile === 'string') aFile = nsFile(aFile);
var stream = FileUtils.openSafeFileOutputStream(aFile, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE);
var binaryStream = Cc["@mozilla.org/binaryoutputstream;1"].createInstance(Ci.nsIBinaryOutputStream);
binaryStream.setOutputStream(stream);
binaryStream.writeByteArray(data, data.length);
FileUtils.closeSafeFileOutputStream(stream);
}
總而言之...
我一直在嘗試使用nsIArrayBufferInputStream http://dxr.mozilla.org/mozilla-central/source/netwerk/base/public/nsIArrayBufferInputStream.idl,但沒有成功。 我試過的代碼:
function fileWrite(file, data, callback) {
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");
let nsFile = Components.Constructor("@mozilla.org/file/local;1", Ci.nsILocalFile, "initWithPath");
if (typeof file == 'string') file = new nsFile(file);
let ostream = FileUtils.openSafeFileOutputStream(file)
let istream = Cc["@mozilla.org/io/arraybuffer-input-stream;1"].createInstance(Ci.nsIArrayBufferInputStream);
istream.setData(data, 0, data.length);
let bstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);
bstream.setInputStream(istream);
//NetUtil.asyncCopy(istream, ostream,
NetUtil.asyncCopy(bstream, ostream,
function(status) {
if (callback) callback(Components.isSuccessCode(status));
}
);
}
ArrayBuffer data
參數是XMLHttpRequest的響應:
function getBinFile(url, dir) {
let nsFile = Components.Constructor("@mozilla.org/file/local;1", Ci.nsILocalFile, "initWithPath");
let oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(oEvent) {
var arrayBuffer = oReq.response;
if (arrayBuffer) {
//let byteArray = new Uint8Array(arrayBuffer);
let byteArray = arrayBuffer;
dir = /\\$/.test(dir) ? dir: dir + '\\';
let file = nsFile(dir + decodeURIComponent(url.split('/').pop()));
fileWrite(file, byteArray);
}
};
oReq.send(null);
}
像這樣打電話:
getBinFile( 'http://....', 'c:\\demo\\');
文件已創建但沒有內容!
我正在回答自己,以防有人偶然發現這個問題...
在Mozilla的Josh Matthews的幫助下,我找到了答案:使用byteLength
而不是length
istream.setData(data, 0, data.byteLength);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.