最近在看firefox中关于下载部分的内容,在网上看到这篇文章,虽然现在用不上,但是也觉得很好,分享下。
Firefox插件开发中用JS实现文件下载
进入全屏
![line](https://i-blog.csdnimg.cn/blog_migrate/42901f02c6aff2532375ca24f9e4d820.gif)
今天收拾电脑,发现有个以前开发Firefox插件时候写的类库----用Javascript实现文件下载。
放到博客上,给自己沉淀一下,以后还会用得上:
var
Baidufe = window.Baidufe || {};
/**
* 处理网络文件的操作,如下载等
* @author 赵先烈
*/
Baidufe.FileNetwork =
function
(){};
/**
* 获取默认的本地目录
*/
Baidufe.FileNetwork.getDefaultDiretory =
function
(){
var
file = Components.classes[
"@mozilla.org/file/directory_service;1"
]
.getService(Components.interfaces.nsIProperties)
.get(
"Home"
,Components.interfaces.nsIFile);
return
file.path;
};
/**
* 选择一个本地存储的目录
*/
Baidufe.FileNetwork.selectDirectory =
function
(){
const nsIFilePicker = Components.interfaces.nsIFilePicker;
var
fp = Components.classes[
"@mozilla.org/filepicker;1"
].createInstance(nsIFilePicker);
fp.init(window,
""
,nsIFilePicker.modeGetFolder);
var
result = fp.show();
if
(result == nsIFilePicker.returnOK) {
return
fp.file.path;
}
else
{
return
null
;
}
};
/**
* 下载文件到本地
* @param {Object} config 下载参数,格式为:
* {
* uri : "",文件源地址
* dir : "" , //本地存储目录
* callback : function(file,fileName){}, //下载完成的回调
* fileName : "" //文件名
* }
*/
Baidufe.FileNetwork.downLoadFile =
function
(config){
var
ios = Components.classes[
"@mozilla.org/network/io-service;1"
].getService(Components.interfaces.nsIIOService);
var
fileURI = ios.newURI(config.uri,
null
,
null
);
var
channel = ios.newChannelFromURI(fileURI);
var
observer = {
onStreamComplete:
function
(loader, context, status, length, result){
var
file = Components.classes[
"@mozilla.org/file/local;1"
].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(config.dir);
if
( !file.exists() || !file.isDirectory() ) {
// if it doesn't exist, create
file.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
}
file.appendRelativePath(config.fileName);
var
stream = Components.classes[
"@mozilla.org/network/safe-file-output-stream;1"
].createInstance(Components.interfaces.nsIFileOutputStream);
stream.init(file, -1, -1, 0);
var
bstream = Components.classes[
"@mozilla.org/binaryoutputstream;1"
].createInstance(Components.interfaces.nsIBinaryOutputStream);
bstream.setOutputStream(stream);
bstream.writeByteArray(result, length);
if
(stream
instanceof
Components.interfaces.nsISafeOutputStream) {
stream.finish();
}
else
{
stream.close();
}
if
(
typeof
config.callback ==
"function"
) {
config.callback(file, config.fileName);
}
}
};
var
streamLoader = Components.classes[
"@mozilla.org/network/stream-loader;1"
].createInstance(Components.interfaces.nsIStreamLoader);
streamLoader.init(observer);
channel.asyncOpen(streamLoader, channel);
};
|