[Uniapp] APP拍照后转换Base64上传
组件(2选1):
1. uni-file-picker : https://uniapp.dcloud.net.cn/component/uniui/uni-file-picker.html
2. u-upload : https://uviewui.com/components/upload.html
思路:
1.图片存到数据库,表设计的字段为byte[] , 在MSSQL中类型为Image
2.前端传参为Base64字符串,后端( C# Convert.FromBase64String() )转换Base64为byte[] , 再存入数据库
Base64转换:
注意!compressIamge方法输出结果会带有“data:image/jpeg;base64,”,存入数据库前可replace('data:image/jpeg;base64,','')
async uploadFilePromiseSync(url) { return new Promise((resolve, reject) => { // #ifdef H5 uni.request({ url: url, method: 'GET', responseType: 'Arraybuffer', success: res => { console.log(res) let base64 = uni.arrayBufferToBase64((res.data)) resolve(base64) }, fail: (e) => { reject(e) } }) // #endif // #ifdef APP uni.compressImage({ src: url, quality: 100, success: (res) => { const tempUrl = res.tempFilePath plus.io.resolveLocalFileSystemURL(tempUrl, (entry) => { entry.file((e) => { let fileReader = new plus.io.FileReader(); fileReader.onload = (r) => { console.log(r.target.result) resolve(r.target.result) } fileReader.readAsDataURL(e) }) }) }, fail: (e) => { reject(e) } }) // #endif }) }
组件方法:
在 u-upload的@afterRead="afterRead"方法里用e.tempFilePaths[0]开始转换Base64 , 或者在 uni-file-picker 的@select="select"方法里用lists[i].url开始转换Base64.
<uni-file-picker fileMediatype="image" :limit="1" @select="select" /> async select(e) { console.log('选择文件:', e) await this.uploadFilePromiseSync(e.tempFilePaths[0]) }
<u-upload accept="image" @afterRead="afterRead" mutiple :maxCount="1" :previewFullImage="true"></u-upload> async afterRead(event) { // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式 let lists = [].concat(event.file) for (let i = 0; i < lists.length; i++) { await this.uploadFilePromiseSync(lists[i].url) } }