前言
文件图片上传,客户端预览是很正常的需求,获取文件的md5特征码也是很正常的,那么,在uniapp中三种环境,h5, 小程序以及 app环境下,如何实现的?
参考:
如何在uniapp中读取文件ArrayBuffer和sha256哈希值,支持H5、APP、小程序
uniapp 没有提供跨平台的 API 来获取文件的 sha256 哈希值和读取文件的 ArrayBuffer,因此需要开发者自己手动兼容各个平台。在小程序端使用FileSystemManager、app 端是plus.io、H5 端是FileReader,这些 API 都是平台特有的,而且实际调用存在各种问题,也缺乏相关教程
ps:只适合小文件上传,大文件的话不要用这个。计算md5的时候采用了sparkMD5,请自行安装。
具体实现
必须要知道的是文件的临时路径,就是:
http://xxxxx 形式的
例如:
// 读取图像文件
uni.chooseImage({
count: 9,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const tempFilePaths = res.tempFilePaths
// tempFilePaths 是一个数组,可以通过索引获取图片路径,比如tempFilePaths[0],我们需要的就是这个路径
},
})
或者
uni.chooseMedia({
count:1,// 限制选取图像数量
mediaType:["image"],// 设置选取资源为图片类型
sourceType:["album","camera"],// 设置图像来源:相册或相机
camera:"back",// 设置相机为后置摄像头
success:(res)=>{
// 获取微信拿到的图片的临时地址并保存到本地
this.photoPath=res.tempFiles[0].tempFilePath;
}
})
},
小程序获取 ArrayBuffer以及读取base64:
arrayBuffer:
// 小程序,filePath 是一个本地文件路径
const fs = uni.getFileSystemManager()
return fs.readFileSync(filePath)
base64:
// (由于uniapp开发所以uni打头)
uni.getFileSystemManager().readFile({// 【重点来啦】人家自提供的转码API
filePath:image.path,// 所需转码图像路径
encoding:"base64",// 转码类型
success:(res)=>{
// 生成base64
let imageBase64='data:image/'+image.type+';base64,'+res.data;
console.log('转base64后:',imageBase64);
}
})
H5获取 ArrayBuffer以及读取base64:
const blobURLToBlob = (url) => {
return new Promise((resolve, reject) => {
var http = new XMLHttpRequest()
http.open('GET', url, true)
http.responseType = 'blob'
http.onload = function (e) {
if (this.status == 200 || this.status === 0) {
resolve(this.response)
} else {
reject(this.status)
}
}
ht