1.view代码
<view class="uploadphoto">
<view class="uploadtit">上传照片view>
<image class="upload" @click="uploadimg" :src="thumbs">image>
view>
2.js代码
<script>
export default {
data() {
return {
thumbs: '', //图片地址
}
},
methods: {
//点击上传图片功能
uploadimg() {
let that = this;
//1.选择图片
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
// console.log('打印图片临时路径:', tempFilePaths[0]);
uni.showLoading({
title: '正在上传'
});
//2.上传图片
const uploadTask = uni.uploadFile({
url:that.host+ 'attachment/upload',
header: {
'token': uni.getStorageSync('token'), //token
},
filePath: tempFilePaths[0], //图片临时路径
name: 'file',
formData: {
"user": 'test'
},
success: (res) => {
console.log((JSON.parse(res.data)).data) //接口返回的线上图片路径
that.thumbs = JSON.parse(res.data).data
uni.hideLoading();
uni.showToast({
title: '上传成功',
icon: 'success',
duration: 2000
});
},
fail: (error) => {
console.log('失败原因', error);
}
});
}
});
},
}
}
</script>