標簽: js uni-app
前情
uni-app是我很喜歡的跨平台框架,它能開發小程序,H5,APP(安卓/iOS),對前端開發很友好,自帶的IDE讓開發體驗也很棒,公司項目就是主推uni-app。
坑位
最近在做一個需求,需要在uni-app下載zip,word,pdf文件並打開瀏覽,發現在安卓下是正常的,但是在IOS下一直失敗。
Why
其實是文件名用中文命名導致的,在IOS下需要對文件名執行一次轉碼,安卓下不需要,不然安卓又無法下載了。
解決方案
在調用uni.saveFile前,對文件名執行轉碼處理。
關鍵代碼
// 下載關鍵測試代碼如下
downloadFileAction() {
const downloadTask = uni.downloadFile({
url: 'http://www.test.com/文件.zip', //僅為示例,並非真實的資源
success: (res) => {
if (res.statusCode === 200) {
console.log('下載成功');
}
let that = this;
uni.saveFile({
tempFilePath: this.fileNameEscape(res.tempFilePath),
success: function(red) {
that.luj = red.savedFilePath
console.log(red)
}
});
}
});
downloadTask.onProgressUpdate((res) => {
console.log('下載進度' + res.progress);
console.log('已經下載的數據長度' + res.totalBytesWritten);
console.log('預期需要下載的數據總長度' + res.totalBytesExpectedToWrite);
});
},
/**
* ios下文件名中文處理
* @param {String} filename
*/
fileNameEscape(filename) {
if (uni.getSystemInfoSync().platform == "ios") {
filename = escape(filename);
}
return filename;
}
參考地址:escape
