微信小程序 — 保存文件到本地的两种方式
第一种:wx.saveFile(Object object)保存文件到本地。
注意:saveFile 会把临时文件移动,因此调用成功后传入的 tempFilePath 将不可用,本地文件存储的大小限制为 10M
wx.chooseImage({
success: function(res) {
const tempFilePaths = res.tempFilePaths
wx.saveFile({
tempFilePath: tempFilePaths[0],
success (res) {
const savedFilePath = res.savedFilePath
}
})
}
})
第二种:FileSystemManager.saveFile(Object object)
保存临时文件到本地。此接口会移动临时文件,因此调用成功后,tempFilePath 将不可用。
此方法存储可以自己定义目录,可以实现需要分账号角色存储的功能。
/* 保存图片 */
save_photo: function () {
const fs = wx.getFileSystemManager()
var isExist = false; //目录是否存在
var that = this;
// 同步接口
try {
fs.accessSync(`${wx.env.USER_DATA_PATH}/photoinvoice/1553115`)
isExist = true;
} catch (e) {
// console.error(e)
}
if (isExist != true) {
// 同步接口,创建目录
try {
fs.mkdirSync(`${wx.env.USER_DATA_PATH}/photoinvoice/1553115`, true)
} catch (e) {
console.error(e)
}
}
// console.log(`${wx.env.USER_DATA_PATH}/photoinvoice/1553114`)
console.log(that.data.src)
wx.getImageInfo({
src: this.data.src,
success: function (res) {
var path = res.path;
console.log("path:" + path) //wxfile://te6786958409efjje46546i5.jpg
//下面获取图片名te6786958409efjje46546i5.jpg
var startPos = path.lastIndexOf("//");
console.log(startPos)
var picName = path.slice(startPos + 2, path.length); //加2是为了从//后面截取。所以+2,把//过滤掉
console.log(picName)
fs.saveFile({
tempFilePath: path,
filePath: `${wx.env.USER_DATA_PATH}/photoinvoice/1553115/${picName}`, //保存的时候必须跟上路径和文件名
success: function (res) {
console.log("保存成功")
console.log(res)
},
fail: function (res) {
console.log("保存失败")
console.log(res)
}
})
}
})
},
版权声明:本文为liu13722785488原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。