/**
* 图片预览
* @ param url 链接
*/
function previewOneImage(url) {
var imgList = [url];//获取img-list
//图片预览
wx.previewImage({
current: url, // 当前显示图片的链接
urls: imgList // 需要预览的图片的链接列表
})
}
/**
* 本地图片上传
*/
function uploadOneImage() {
return new Promise(function (resolve, reject) {
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album'],
success(res) {
const tempFilePaths = res.tempFilePaths[0];
// resolve(tempFilePaths)//可直接返回临时链接,也可直接返回res
resolve(res)
},
fail(res) {
}
})
})
}
/**
* 相机拍摄
*/
function uploadByCamera() {
return new Promise(function (resolve, reject) {
wx.chooseImage({
count: 1,
sizeType: ['original'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有'album', 'camera'
success(res) {
const tempFilePaths = res.tempFilePaths[0];
resolve(res)
},
fail(res) {
}
})
})
}
/**
* 视频拍摄
* @param maxDuration时长
* @param from 上传方式:相册 album 相机拍摄 camera
*/
function chooseVideo(maxDuration, from) {
//album 相册选择 camera 相机拍摄
return new Promise(function (resolve, reject) {
wx.chooseVideo({
sourceType: [from],
maxDuration: maxDuration,
camera: 'back',
success(res) {
const tempFilePath = res.tempFilePath;
const time = res.duration;
const size = res.size;//返回时间为字节B,转换1M=1024KB 1Kb=1024B
resolve(res)
},
fail(err) {
reject(err)
}
})
})
}
/**
* 预览pdf
* @param {*} post_res 接口返回数据
* @param {*} dirPath 写入本地路径中的微信缓存key值
* @param {*} fileType 文件类型,指定文件类型打开文件
*/
function toPreviewPDF(post_res, dirPath, fileType) {
return new Promise(function (resolve, reject) {
const FileSystemManager = wx.getFileSystemManager();
const filePath = wx.env.USER_DATA_PATH + "/" + Date.now();
removeSave(dirPath).then(remove_res => {
FileSystemManager.writeFile({
filePath: filePath,
data: post_res,
encoding: "binary",//必填
success(res) {
wx.openDocument({ // 打开文档
filePath: filePath, //拿上面存入的文件路径
showMenu: true, // 显示右上角菜单
fileType: fileType,
success: function (res) {
console.log('打开' + fileType + '成功')
wx.setStorageSync(dirPath, filePath);
resolve(filePath)
},
fail:function(err){
reject(err)
}
})
}
})
})
})
}
/**
* 清除临时本地文件,防止多次保存报错
* @param {*} dirPath 小程序缓存key值
*/
function removeSave(dirPath) {
return new Promise(function (resolve, reject) {
// 把文件删除后再写进,防止超过最大范围而无法写入
const fsm = wx.getFileSystemManager(); //文件管理器
fsm.readdir({ // 获取文件列表
dirPath: wx.env.USER_DATA_PATH,// 当时写入的文件夹
success(res) {
let dir = wx.getStorageSync(dirPath);
if (!dir) {
} else {
fsm.unlink({
filePath: dir,
success(res) {
console.log('readdir文件删除成功:', res)
},
fail(e) {
console.log('readdir文件删除失败:', e)
}
})
}
resolve(dirPath)
}
})
})
}
微信小程序图片、视频上传、预览PDF
最新推荐文章于 2024-12-24 17:54:37 发布