2009-05-23 12:25

[Firefox 套件開發] 建立檔案選取對話匡並讀取檔案



//*建立檔案選取對話匡*/
const nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.
classes["@mozilla.org/filepicker;1"].
createInstance(nsIFilePicker);

// 對話匡標題及開啟形式
fp.init(window, "讀取文件", nsIFilePicker.modeOpen);
/*
常數 數值 描述
modeOpen 0 載入一個檔案或目錄
modeSave 1 儲存一個檔案或目錄
modeGetFolder 2 選擇一個資料夾目錄
modeOpenMultiple 3 載入多個檔案
*/


// 預設副檔名
fp.defaultExtension = 'txt';
// 預設檔名
fp.defaultString = 'file_name';
// 檔案類型過濾
fp.appendFilter("純文字檔","*.txt");

// 使用檔案類型過濾
fp.appendFilters(nsIFilePicker.filterHTML | nsIFilePicker.filterXML);
/*
常數 數值 描述
filterAll 0x01 符合 *.* 的副檔名
filterHTML 0x02 符合 *.html, *.htm 的副檔名
filterText 0x04 符合 *.txt 的副檔名
filterImages 0x08 符合 *.png, *.gif, *.jpg, *.jpeg 的副檔名
filterXML 0x10 符合 *.xml 的副檔名
filterXUL 0x20 符合 *.xul 的副檔名
filterApps 0x40 符合系統平台的應用程式類型
*/


// 顯示對話匡
var result = fp.show();

/*
常數 數值 描述
returnOK 0 當使用者點擊對話匡中的"確認"
returnCancel 1 當使用者點擊對話匡中的"取消"
returnReplace 2 當使用者選擇一個已存在的檔案並同意複寫
*/
if (result != nsIFilePicker.returnOK) {
//建立檔案資料流
var stream = Components.
classes["@mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
var cstream = Components.
classes["@mozilla.org/intl/converter-input-stream;1"].
createInstance(Components.interfaces.nsIConverterInputStream);

// 開啟檔案資料流
stream.init(fp.file, -1, 0, 0);
// 設定檔案讀取編碼方式
cstream.init(stream, "UTF-8", 0, 0);

var templates='';
let (str = {}) {
// 讀取整個文件,並把它放在 str.value
cstream.readString(-1, str);
templates = str.value;
}

// 顯示檔案內容
alert(templates);


// 關閉檔案資料流
cstream.close();
stream.close();
}


參考來源:
Open and Save Dialogs - MDC
nsIFilePicker - MDC
Reading textual data - MDC
File I/O - MDC
nsIInputStream - MDC

0 回應: