uni-app实现type=file并且实现图片上传
<view class="btn-choice-pic" ref="input">
<view class="" @click="choicePic">
选择图片
</view>
</view>
mounted() {
// 创建附件上传
var _self = this;
var input = document.createElement('input'); //创建元素
input.type = 'file' //添加file类型
input.ref = 'myChangePic' //添加file类型
input.className = 'addinput'
input.style.position = 'absolute'
input.style.top = '0'
input.style.width = '80%'
input.style.left = '10%'
input.style.height = '50px'
input.style.lineHeight = '50px'
input.style.opacity = '0'
input.onclick = (event) => {
console.log('ars')
_self.choicePic(input, event)
}
this.$refs.input.$el.appendChild(input)
},
methods:{
choicePic(input, event) {
this.jiequShow = 1
// this.$refs.myChangePic.click()
var that = this;
let count = 1; //默认上传的图片数量
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (res) => {
if (that.imgList.length < count) {
for (var i = 0; i < res.tempFilePaths.length; i++) {
that.urlToBase(res.tempFilePaths[i]).then(res => {
that.imgList = that.imgList.concat(res)
})
}
} else {
that.imgList = [] //设置为空数组
for (var i = 0; i < res.tempFilePaths.length; i++) {
that.urlToBase(res.tempFilePaths[i]).then(res => {
that.imgList = that.imgList.concat(res)
})
}
}
}
});
},
urlToBase(url) {
return new Promise((resolve, reject) => {
uni.request({
url: url,
method: 'GET',
responseType: 'arraybuffer',
success: res => {
let base = wx.arrayBufferToBase(res.data); //把arraybuffer转成base
base = 'data:image/jpeg;base,' + base //不加上这串字符,在页面无法显示的
this.imgs = base
console.log(base)
resolve(base)
},
fail: err => {
reject(err)
}
})
})
},
}