FileSystemManager.readFileSync

2020-08-26 16:17 更新

解釋:讀取本地文件內(nèi)容的同步接口。

Web 態(tài)說明:受瀏覽器限制,Web 態(tài)不支持文件系統(tǒng)相關(guān)功能,調(diào)用該方法會(huì)拋出一個(gè)標(biāo)準(zhǔn)的 Error 對(duì)象。

方法參數(shù):String filePath, String encoding

filePath參數(shù)說明:文件/目錄路徑。“本地用戶文件”須以 swan.env.USER_DATA_PATH 開頭(如 'swan.env.USER_DATA_PATH' + '/demo.txt'),否則認(rèn)為是“代碼包文件”(如 'asset/bg.jpg')。不支持相對(duì)路徑。

encoding參數(shù)說明:指定讀文件的字符編碼,默認(rèn) 'utf8'。

encoding 的合法值

同步返回參數(shù)說明:

若接口調(diào)用失敗,會(huì)拋出一個(gè)標(biāo)準(zhǔn)的Error對(duì)象

示例 

在開發(fā)者工具中打開


圖片示例

代碼示例

<view class="wrap">
    <button type="primary"  bindtap="readFileSync">讀取本地文件內(nèi)容</button>
</view>
Page({
    data: {
        filePath: ''
    },
    onLoad() {
        this.fileSystemManager = swan.getFileSystemManager();
        swan.downloadFile({
            url: 'https://smartprogram.baidu.com/docs/img/logo.png',
            success: res => {
                swan.showToast({
                    title: `文件預(yù)下載完成,臨時(shí)路徑為${res.tempFilePath}`,
                    icon: 'none'
                });
                // 此為 “本地臨時(shí)文件” 路徑。
                this.data.filePath = res.tempFilePath;
            }
        });
    },
    readFileSync() {
        try {
            let result = this.fileSystemManager.readFileSync(
                this.data.filePath
            );
            swan.showToast({
                title: '讀取成功',
                icon: 'none'
            });
            console.log('readFileSync success', result);
        }
        catch (err) {
            swan.showToast({
                title: JSON.stringify(err),
                icon: 'none'
            });
            console.log('readFileSync fail', err);
        }
    }
});


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)