Uniapp 拍照以及摄像功能

<template>
    <view class="content">
        <view class="margin-bottom padding-sm radius shadow bg-white">
            <image :src="imagePath" mode="widthFix"></image>
        </view>

        <button class="margin-lr-xl cu-btn bg-red shadow-blur round lg" @click="takePhoto">房间 {{room}} 拍照</button>

        <button class="margin-lr-xl cu-btn bg-red shadow-blur round lg" @click="chooseVideo()">录像</button>
        <!--         <view class="cu-form-group margin-top">
            <textarea maxlength="-1" :disabled="modalName!=null" @input="textareaAInput"
                placeholder="这里是备注区域"></textarea>
        </view> -->

        <!-- 显示当前的 modalName 值 -->
        <view>当前显示路径</view>
        <view class="auto-wrap margin-tb padding-sm radius shadow bg-white"> {{ imagePath }}</view>
        <view>上传返回路径</view>
        <view class="auto-wrap margin-tb padding-sm radius shadow bg-white"> {{ returnImagePath }}</view>

        <view>当前显示路径</view>
        <view class="auto-wrap margin-tb padding-sm radius shadow bg-white"> {{ videoPath }}</view>
        <view>上传返回路径</view>
        <view class="auto-wrap margin-tb padding-sm radius shadow bg-white"> {{ returnVideoPath }}</view>
        <!-- <view class="auto-wrap margin-tb padding-sm radius shadow bg-white"> {{ textareaAValue }}</view> -->
        <view class="box footn" v-if="isShown">
            <view class="cu-bar btn-group">
                <button @click="goUpload()" class="cu-btn bg-green shadow-blur round lg">开始上传</button>
            </view>
        </view>
    </view>
</template>

<script>
    export default {
        name: 'CameraPage',
        data() {
            return {
                room: '1',
                isShown: false, // 初始状态为隐藏
                imagePath: '/static/98035487-eac1-4d24-928f-79f3fa3724f3.jpg',
                modalName: null,
                textareaAValue: '',
                token: "",
                returnImagePath: '',
                token: "",
                videoPath: '',
                returnVideoPath: ''
            }
        },
        onLoad() {
            this.token = uni.getStorageSync('token'); //用户信息
            this.room = uni.getStorageSync('room'); //用户信息
            this.checkToken()
        },
        methods: {
            checkToken() {
                uni.request({
                    url: "/app/getCurrentUser",
                    method: 'POST',
                    data: '',
                    header: {
                        'content-type': 'application/json', // 根据后端要求设置合适的Content-Type
                        'Authorization': this.token
                    },
                    success: (res) => {
                        console.log('请求成功:', res);
                        if (res.statusCode === 200) {
                            if (res.data.code === 401) {
                                uni.showToast({
                                    title: '您token过期,请重新登录',
                                    icon: "none"
                                });
                                uni.redirectTo({
                                    url: '/pages/user/index'
                                });
                            }
                        } else {
                            // 处理错误响应
                            console.error('错误状态码', res.statusCode);
                            return;
                        }
                    },
                    fail: (err) => {
                        console.error('请求失败', err);
                    }
                });
            },
            takePhoto() {
                if (process.env.TARO_ENV === 'app') { // 判断是否在原生App环境中
                    // 检查权限是否已获取
                    uni.getSetting({
                        success: (res) => {
                            if (!res.authSetting['scope.camera']) {
                                // 请求权限
                                uni.authorize({
                                    scope: 'scope.camera',
                                    success: () => {
                                        this.chooseImage();
                                    },
                                    fail: () => {
                                        uni.showModal({
                                            title: '需要权限',
                                            content: '需要获取摄像头权限才能拍照',
                                            showCancel: false
                                        });
                                    }
                                });
                            } else {
                                this.chooseImage();
                            }
                        }
                    });
                } else {
                    this.chooseImage();
                }
            },
            // 拍照或选择图片
            chooseImage() {
                uni.chooseImage({
                    count: 1, // 默认9, 选择数量限制
                    sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
                    success: (res) => {
                        const tempFilePaths = res.tempFilePaths;
                        this.$set(this, 'imagePath', tempFilePaths[0]);

                        this.isShown = true;
                    }
                });
            },
            goUpload() {
                uni.uploadFile({
                    url: 'http://120.27.13.29:8888/common/upload',
                    filePath: this.videoPath,
                    name: 'file',
                    formData: {
                        'room': this.room
                    },
                    header: {
                        'Authorization': this.token // 添加 token 到请求头
                    },
                    success: (res) => {
                        const data = JSON.parse(res.data);
                        this.returnVideoPath = data.url
                        uni.showToast({
                            title: data.msg,
                            icon: "none"
                        });
                        this.isShown = false;
                    }
                })

            },
            textareaAInput(e) {
                this.textareaAValue = e.detail.value
            },
            chooseVideo() {
                uni.chooseVideo({
                    count: 1,
                    sourceType: ['camera'],
                    maxDuration: 60, // 最大视频录制时长(秒)
                    success: (res) => {
                        const videotempFilePath = res.tempFilePath;
                        console.log('选择视频成功,返回的参数URL:', videotempFilePath);
                        this.isShown = true;
                        console.log('选择视频成功,返回的参数:', res);
                        // 可以使用 res.tempFilePath 获取视频的本地路径
                        // 如果你需要将路径存储在组件的数据属性中,可以这样做
                        this.videoPath = videotempFilePath;
                    },
                    fail: (err) => {
                        console.error('选择视频失败:', err);
                    }
                });
            }
        }
    }
</script>

<style>
    .content {
        display: flex;
        flex-direction: column;
        margin: 30rpx;
        /* align-items: center; */
        /* justify-content: center; */
    }

    .footn {
        position: fixed;
        width: 90%;
        bottom: 20rpx;
        z-index: 1024;
        /* box-shadow: 0 -1upx 6upx rgba(0, 0, 0, 0.1); */
    }

    .auto-wrap {
        white-space: pre-wrap;
        word-wrap: break-word;
    }
</style>

### 实现 UniApp 的照片选择与拍摄功能UniApp 中实现照片的选择与拍摄功能主要依赖于 `uni.chooseImage` 方法以及其参数配置。以下是具体方法的详细介绍: #### 使用 `uni.chooseImage` 进行照片选择或拍摄 通过 `sourceType` 参数可以控制图片来源为相册 (`album`) 或者相机 (`camera`)。如果希望支持两种方式,则可将其设为数组形式 `[ 'album', 'camera' ]`。 ```javascript function chooseOrTakePhoto() { uni.chooseImage({ count: 1, // 设置最多可以选择的照片数量 sizeType: ['original', 'compressed'], // 原图或者压缩图 sourceType: ['album', 'camera'], // 来源既可以是相册也可以是相机 success(res) { // 成功回调函数 const tempFilePaths = res.tempFilePaths; console.log('临时路径:', tempFilePaths); }, fail(err) { // 失败回调函数 console.error('操作失败:', err); } }); } ``` 上述代码片段展示了如何让用户从相册或相机获取一张图片,并打印出所选图片的临时文件路径[^3]。 #### 调用设备摄像头单独完成拍照 当仅需提供拍照选项时,可以通过调整 `sourceType` 参数来限定输入来源仅为相机(`camera`)。 ```javascript function takePhotoOnly() { uni.chooseImage({ count: 1, sizeType: ['original'], sourceType: ['camera'], // 限定只允许使用相机 success(res) { const photoPath = res.tempFilePaths[0]; console.log('拍下的照片路径:', photoPath); }, fail(err) { console.error('拍照失败:', err); } }); } ``` 此部分实现了纯粹基于相机的应用场景下捕捉图像的能力。 #### 文件上传至服务器端处理逻辑 一旦获得了本地存储中的图片资源地址之后,就可以利用 `uni.uploadFile` 将这些数据提交给远程服务端保存起来。 ```javascript function uploadSelectedImage(filePath) { uni.uploadFile({ url: 'https://example.com/upload', // 替换为目标服务器接口URL filePath: filePath, name: 'file', formData: {}, // 如果有额外表单字段则在此处定义 success(uploadRes) { console.log('上传成功响应:', JSON.parse(uploadRes.data)); }, fail(error) { console.error('上传错误:', error); } }); } // 结合前面的方法,在选取/拍摄完成后立即执行上传动作 chooseOrTakePhoto().then((filePath) => uploadSelectedImage(filePath)); ``` 以上脚本说明了怎样把刚刚得到的一张新近摄取下来的影像资料传送到网络后台去进一步加工管理[^2]。 ### 注意事项 - 需要确保项目已申请必要的权限(如访问媒体库、开启摄像机等),特别是在 Android 平台上可能还需要动态请求权限。 - 对应的服务端API应当能够接收multipart/form-data类型的POST请求,并妥善解析其中包含的实际二进制流内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值