uniapp云开发之云函数+头像上传案例

2021-05-30  本文已影响0人  似朝朝我心

界面预览:



云开发控制台拿到的数据:


云函数编写:

'use strict';
exports.main = async (event, context) => {
    //event为客户端上传的参数
    console.log('event : ', event)
    
    //返回数据给客户端
    return new Promise((resolve,reject) => {
        const db = uniCloud.database()
        db.collection("user").add(event).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
};


代码:

<template>
    <view class="content">
        <text style="font-weight: bolder;">头像上传</text>
        <!-- 图片上传区 -->
        <form action="" @submit="formSubmit">
            
            <view @tap="chooseFile" style="width: 400upx;height: 400upx;background-color: #C0C0C0;">
                <image :src="userInfo.imgSrc" style="width: 100%;height: 100%;" mode=""></image>
            </view>
            用户:<input style="width: 100%;border: 1upx solid #007AFF;" type="text" name="userName" id="">
            密码:<input style="width: 100%;border: 1upx solid #007AFF;" type="text" name="password" password="" value="" />
            <button type="primary" form-type="submit" style="margin-top: 20upx;">确认上传</button>
        </form>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                userInfo:{
                    imgSrc:'',
                    userName:'',
                    password:''
                }
            }
        },
        onLoad() {
            
        },
        methods: {
            chooseFile(){
                uni.chooseImage({//选择图片
                    count:1,
                    success: (res) => {
                        console.log('头像缓存成功')
                        this.userInfo.imgSrc = res.tempFilePaths[0]
                    }
                })
            },
            formSubmit(e){//处理表单
                let that = this
                console.log(e.detail.value)
                that.userInfo.userName = e.detail.value.userName
                that.userInfo.password = e.detail.value.password
                //上传操作
                uniCloud.callFunction({
                    name:"upLoad",
                    data:that.userInfo
                }).then(res => {
                    console.log(res,'数据上传成功')
                }).catch(err =>{
                    console.log(err)
                })
            }
        }
    }
</script>

<style>
    .content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

</style>

上一篇下一篇

猜你喜欢

热点阅读