uniapp上传图片
选择图片
这里定义js文件
export default {
/**
* 选择图片
* @param number num
* @param {Object} params
* @param {Object} callback
* @param string url
* return array
*/
upload: function(num, params, callback, url) {
// 根据个人需求传参数 ....
// #ifdef MP-WEIXIN
var app_type = 'weapp';
var app_type_name = '微信小程序';
// #endif
// 参数
var data = {
app_type: app_type,
app_type_name: app_type_name
}
data = Object.assign(data, params);
var _self = this;
uni.chooseImage({
count: num,
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 从相册或者拍照
success: async function(res) {
console.log('选择图片成功回调:', res)
const tempFilePaths = res.tempFilePaths;
var _data = data;
var imgs = [];
for (var i = 0; i < tempFilePaths.length; i++) {
// 执行上传图片方法,返回已上传的相关图片路径
var path = await _self.upload_file_server(tempFilePaths[i], _data, url);
imgs.push(path);
}
typeof callback == 'function' && callback(imgs);
}
});
},
}
上传图片
/**
* 图片上传
*/
upload_file_server(tempFilePath, data, url = "") {
// 处理URL
var uploadUrl = '';
if (url) {
uploadUrl = `${Config.baseUrl}${url}`
} else {
uploadUrl = `${Config.baseUrl}/api/upload/${data.path}`;
}
return new Promise((resolve, reject) => {
uni.uploadFile({
url: uploadUrl,
filePath: tempFilePath,
name: 'file',
formData: data,
success: function(res) {
var tmpData = JSON.parse(res.data);
console.log('上传文件返回数据:', tmpData)
// 根据个人需求返回相关数据
if (tmpData.code >= 0) {
resolve(tmpData.data.pic_path);
} else {
reject("error");
}
}
});
});
},
使用
<view class="idenItem" @click="addImgTap()">
<image class="whFull" :src="card_front" mode="aspectFill"></image>
</view>
addImgTap(type) {
this.$util.upload(1, {
path: 'authimg'
}, res => {
console.log('已上传的图片资源', res);
});
}