Uniapp 图片上传代码示例 - 简单易懂
以下是一个基于 Uniapp 的图片上传代码示例:
- 在 template 中添加上传按钮:
<template>
<view>
<button @click="upload">上传图片</button>
</view>
</template>
- 在 script 中添加上传事件:
<script>
export default {
methods: {
upload() {
uni.chooseImage({
count: 1, // 选择图片的数量
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: (res) => {
const tempFilePaths = res.tempFilePaths
this.uploadImage(tempFilePaths[0])
}
})
},
uploadImage(filePath) {
uni.uploadFile({
url: 'http://your.upload.api', // 上传地址
filePath: filePath,
name: 'file',
header: {
'content-type': 'multipart/form-data'
},
success: (res) => {
// 上传成功后的操作
},
fail: (error) => {
// 上传失败后的操作
}
})
}
}
}
</script>
- 在 manifest.json 中添加权限:
{
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序定位"
},
"scope.writePhotosAlbum": {
"desc": "你的相册将用于保存图片"
}
}
}
需要注意的是,上传图片需要用户授权,因此需要在 manifest.json 中添加相应的权限。同时,在上传成功或失败后,需要进行相应的操作,例如提示用户上传结果或刷新页面等。
原文地址: https://www.cveoy.top/t/topic/lUQp 著作权归作者所有。请勿转载和采集!