2009-05-23 12:36

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



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

// 對話匡標題及開啟形式
fp.init(window, "儲存文件", nsIFilePicker.modeSave);
/*
常數 數值 描述
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.returnCancel) {
//建立檔案資料流
var stream = Components.
classes["@mozilla.org/network/file-output-stream;1"].
createInstance(Components.interfaces.nsIFileOutputStream);

// 移除已存在檔案文件
if(fp.file.exists()){fp.file.remove(true);}
// 建立新檔案文件
fp.file.create(fp.file.NORMAL_FILE_TYPE, 0666);

// 開啟檔案資料流
stream.init(fp.file, 0x02, 0x200, null);

var str = "test string"

// 將字串寫入檔案文件
stream.write(str, str.length);

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


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

0 回應: