快應用中的保存圖片,有坑,踩着就中了,這裏也要區分華爲和其他廠商,雖然用調試器,在華爲和官方提供的都不會出現問題,但是,在應用上線後就出現華爲手機無法保存
1.不同點
- 華爲手機在下載圖片時要顯示的定義filename字段
- 先將圖片下載爲臨時文件,然後在圖片下載完成後,進行保存到本地
- 使用request.download進行下載,在這個api中加入filename字段,我這裏將當前時間的時間戳作爲下載的文件名,然後分割圖片的網絡路徑,獲取到圖片的後綴名
let photoPath = 'http://xxxxxxx.png';
let list = photoPath.split('.');
/* 用時間來作爲圖片的名字 */
let timeValue = new Date().valueOf();
/* 獲取圖片後綴 */
let photoExt = list[list.length - 1];
/* 設置要保存的圖片名 */
let filename = `${timeValue}.${photoExt}`;
/* 然後加入filename字段,進行下載操作後對下載任務進行監聽 */
- 之後用request.onDownloadComplete來監聽下載任務,若返回1000則下載任務失敗
- 下載成功後使用media.saveToPhotosAlbum來保存圖片
let photoPath = 'http://xxxxxxx.png';
let list = photoPath.split('.');
/* 用時間來作爲圖片的名字 */
let timeValue = new Date().valueOf();
/* 獲取圖片後綴 */
let photoExt = list[list.length - 1];
/* 設置要保存的圖片名 */
let filename = `${timeValue}.${photoExt}`;
request.download({
url: photoPath,
filename: filename,
success: data => {
/* 監聽下載任務:1000下載失敗,1001下載任務不存在 */
request.onDownloadComplete({
token: data.token,
success: data => {
/* 保存圖片 */
media.saveToPhotosAlbum({
uri: data.uri,
success: () => {
prompt.showToast({
message: '圖片保存成功!'
})
},
fail: (data, code) => {
if(code == 201) {
prompt.showToast({
message: '授權成功後才能保存圖片哦'
})
} else if(code == 202) {
prompt.showToast({
message: '請刷新後重試'
})
} else if(code == 300) {
prompt.showToast({
message: 'I/O錯誤,圖片保存失敗'
})
}
}
})
},
fail: (data, code) => {
if(code == 1000) {
prompt.showToast({
message: '圖片下載失敗'
})
} else if(code == 1001) {
prompt.showToast({
message: '下載任務不存在'
})
}
}
})
},
fail: () => {
}
})