uniapp实现拍照并上传base64格式的图片(记录一下~)

html结构

……

    
        
    


图片列表
序号 图片 操作
{{ index + 1 }}
……

安装image-tools image-tools - DCloud 插件市场

根据安装的路径引入image-tools插件

import { pathToBase64, base64ToPath } from '@/js_sdk/mmmm-image-tools/index.js'

调用uni.chooseImage 

getPic(){
    let that = this;
	uni.chooseImage({
	    count: 9, // 最多可以选择的图片张数,默认9
		sizeType: ['original', 'compressed'], //original 原图,compressed 压缩图,默认二者都有
		sourceType: ['camera','album'], //album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
		// success: function (res) {//如果只需要上传一张图片,则不需要循环
		// 	// console.log(res);
		// 	pathToBase64(res.tempFilePaths[0]).then(base64 => {//将图片转为base64
		//      console.log(base64)
		// 		that.picArr.push({IMAGE_STREAM:base64})
		// 	}).catch(error => {
		// 			console.error(error)
		// 		})
		// that.picList.push(res.tempFilePaths[0])
		// }
		success:(res) => { //上传多张图片
		//循环遍历res.tempFilePaths将每一个图像路径转换为base64
		for(let i=0;i {
			    that.picArr.push({IMAGE_STREAM:base64})
			}).catch(error => {
			    console.error(error)
			})
			that.picList.push(res.tempFilePaths[i])
			}
		}
	})
}
			

调用后端接口

sub(){
    uni.request({
        url: this.$apicore.apicore + '/API/Task/AddLLTestData',
		method: 'POST',
		header: {
		    'content-type': 'application/json',
			'token':this.token
		},
		data:{
		    IMAGE_STREAMS_LIST:this.picArr
		},
		success:res=>{
		    if(res.data.code == 200){
			    uni.showToast({
				    title: '上传成功!',
					icon: 'success',
					duration: 1500
				});
				this.picArr = [];
				this.picList = [];
			}else{
				uni.showModal({
				    title: '上传失败!',
					content: res.data.msg,
					showCancel: false,
					success: res => {
					    if (res.confirm) {
						    // 点击确定之后的逻辑……
						}
					}
				});
			}
		}				
	})
},
			

你可能感兴趣的:(uni-app,vue.js,前端)