uni-app实现图片和视频上传功能

使用uni-app实现点击上传,既可以上传视频,有可以上传图片,图片预览,删除图片和视频功能,最终效果如下。uni-app里面没有提供同时上传视频和图片这个插件,只能靠自己手写,

 

 

 1.页面布局

通过uni-app提供的标签,进行页面布局,这里就不多讲了,uni-app提供的有这个案例,可以直接把他们的样式拷贝过来修改一下就行。

<view class="uni-uploader-body">
                        <view class="uni-uploader__files">
                            <!-- 图片 -->
                           <block v-for="(image,index) in imageList" :key="index">
                                <view class="uni-uploader__file">
                                    <view class="icon iconfont icon-cuo" @tap="delect(index)"></view>
                                    <image class="uni-uploader__img" :src="image" :data-src="image" @tap="previewImage"></image>
                                </view>
                            </block>
                            <!-- 视频 -->
                            <view class="uni-uploader__file" v-if="src">
                                <view class="uploader_video">
                                    <view class="icon iconfont icon-cuo" @tap="delectVideo"></view>
                                    <video :src="src" class="video"></video>
                                </view>
                            </view>
                            <view class="uni-uploader__input-box" v-if="VideoOfImagesShow">
                                <view class="uni-uploader__input" @tap="chooseVideoImage"></view>
                            </view>
                        </view>
                    </view>

1.在data定义一些变量

data() {
            return {
                imageList:[],//图片
                src:"",//视频存放
                sourceTypeIndex: 2,
                sourceType: ['拍摄', '相册', '拍摄或相册'],
          VideoOfImagesShow:true, cameraList: [{ value:
'back', name: '后置摄像头', checked: 'true' }, { value: 'front', name: '前置摄像头' }, ], } },

3.通过使用uni-app提供的api​显示操作菜单,在methods写这个方法,通过判断来,选择的是图片还是视频,根据选择的tabindex选择,然后调用对应的方法即可

chooseVideoImage(){
                uni.showActionSheet({
                    title:"选择上传类型",
                    itemList: ['图片','视频'],
                    success: (res) => {
                        console.log(res)
                        if(res.tapIndex == 0){
                            this.chooseImages()
                        } else {
                            this.chooseVideo()
                        }
                    }
                })
            },

4.上传图片功能,也是通过uni-app提供的chooseImages来实现

chooseImages(){
				// 上传图片
				uni.chooseImage({
					count: 4, //默认9
					// sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
					sourceType: ['album','camera'], //从相册选择
					success:(res)=> {
						let igmFile = res.tempFilePaths;
						uni.uploadFile({
							url:this.config.fileUrl,
							method:"POST",
							header:{
								'Authorization':'bearer '+ uni.getStorageSync('token'),
								'Content-Type':'multipart/form-data'
							},
							filePath:igmFile[0],
							name:'file',
							success: (res) =>{
								// let imgUrls = JSON.parse(res.data); //微信和头条支持
								let imgUrls = res.data //百度支持
								this.imagesUrlPath = this.imagesUrlPath.concat(imgUrls.result.filePath);
								this.imageList = this.imageList.concat(imgUrls.result.filePath); //微信
								if(this.imageList.length>=4) {
									this.VideoOfImagesShow = false;
								} else {
									this.VideoOfImagesShow = true;
								}
							}
						})
						// this.imageList = this.imageList.concat(res.tempFilePaths)  //头条
					},
				});
			},

  

5.图片预览功能,urls必须要接受的是一个数组

previewImage: function(e) {
				//预览图片
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.imageList
				})
			},

 6.点击图片删除功能,点击对应的图片,根据index索引值进行删除

delect(index){
                uni.showModal({
                    title: "提示",
                    content: "是否要删除该图片",
                    success: (res) => {
                        if (res.confirm) {
                            this.imageList.splice(index, 1)
                        }
                    }
                })
            },

7.实现视频上传功能

chooseVideo(){
                // 上传视频
                uni.chooseVideo({
                    maxDuration:60,
                    count: 1,
                    camera: this.cameraList[this.cameraIndex].value,
                    sourceType: ['album'],
                    success: (responent) => {
                        let videoFile = responent.tempFilePath;
                        uni.uploadFile({
                            url:this.config.fileUrl,
                            method:"POST",
                            header:{
                                'Authorization':'bearer '+ uni.getStorageSync('token')
                            },
                            filePath:videoFile,
                            name:'file',
                            success: (res) => {                    
                                // let videoUrls = JSON.parse(res.data) //微信和头条支持
                                let videoUrls = res.data //百度支持
                                this.imagesUrlPath = this.imagesUrlPath.concat(videoUrls.result.filePath);
                                this.src = videoUrls.result.filePath; //微信
                                if(this.src) {
                                    this.itemList = ['图片']
                                } else {
                                    this.itemList = ['图片','视频']
                                }
                                
                            }
                        })
                        // this.src = responent.tempFilePath;  //头条
                    }
                })
            },

 

8.点击视频删除功能

delectVideo(){
                uni.showModal({
                    title:"提示",
                    content:"是否要删除此视频",
                    success:(res) =>{
                        if(res.confirm){
                            this.src = ''
                        }
                    }
                })
            },

最终代码

<template>
    <view class="burst-wrap">
        <view class="burst-wrap-bg">
            <view>
                <!-- 信息提交 -->
                <view class="burst-info">
                    <view class="uni-uploader-body">
                        <view class="uni-uploader__files">
                            <!-- 图片 -->
                           <block v-for="(image,index) in imageList" :key="index">
                                <view class="uni-uploader__file">
                                    <view class="icon iconfont icon-cuo" @tap="delect(index)"></view>
                                    <image class="uni-uploader__img" :src="image" :data-src="image" @tap="previewImage"></image>
                                </view>
                            </block>
                            <!-- 视频 -->
                            <view class="uni-uploader__file" v-if="src">
                                <view class="uploader_video">
                                    <view class="icon iconfont icon-cuo" @tap="delectVideo"></view>
                                    <video :src="src" class="video"></video>
                                </view>
                            </view>
                            <view class="uni-uploader__input-box" v-if="VideoOfImagesShow">
                                <view class="uni-uploader__input" @tap="chooseVideoImage"></view>
                            </view>
                        </view>
                    </view>


                </view>
            </view>
        </view>
    </view>
</template>

<script>
    var sourceType = [
            ['camera'],
            ['album'],
            ['camera', 'album']
        ]
    export default {
        data() {
            return {
                imageList:[],//图片
                src:"",//视频存放
                sourceTypeIndex: 2,
                checkedValue:true,
                checkedIndex:0,
                sourceType: ['拍摄', '相册', '拍摄或相册'],
                cameraList: [{
                        value: 'back',
                        name: '后置摄像头',
                        checked: 'true'
                    },
                    {
                        value: 'front',
                        name: '前置摄像头'
                    },
                ],
                cameraIndex: 0,
                VideoOfImagesShow:true,
            }
        },
        onUnload() {
            this.src = '',
            this.sourceTypeIndex = 2,
            this.sourceType = ['拍摄', '相册', '拍摄或相册'];
        },
        methods: {
            chooseVideoImage(){
                uni.showActionSheet({
                    title:"选择上传类型",
                    itemList: ['图片','视频'],
                    success: (res) => {
                        console.log(res)
                        if(res.tapIndex == 0){
                            this.chooseImages()
                        } else {
                            this.chooseVideo()
                        }
                    }
                })
            },
            chooseImages(){
                // 上传图片
                uni.chooseImage({
                    count: 4, //默认9
                    // sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
                    sourceType: ['album','camera'], //从相册选择
                    success:(res)=> {
                        let igmFile = res.tempFilePaths;
                        uni.uploadFile({
                            url:this.config.fileUrl,
                            method:"POST",
                            header:{
                                'Authorization':'bearer '+ uni.getStorageSync('token'),
                                'Content-Type':'multipart/form-data'
                            },
                            filePath:igmFile[0],
                            name:'file',
                            success: (res) =>{
                                // let imgUrls = JSON.parse(res.data); //微信和头条支持
                                let imgUrls = res.data //百度支持
                                this.imagesUrlPath = this.imagesUrlPath.concat(imgUrls.result.filePath);
                                this.imageList = this.imageList.concat(imgUrls.result.filePath); //微信
                                if(this.imageList.length>=4) {
                                    this.VideoOfImagesShow = false;
                                } else {
                                    this.VideoOfImagesShow = true;
                                }
                            }
                        })
                        // this.imageList = this.imageList.concat(res.tempFilePaths)  //头条
                    },
                });
            },
            chooseVideo(){
                // 上传视频
                uni.chooseVideo({
                    maxDuration:60,
                    count: 1,
                    camera: this.cameraList[this.cameraIndex].value,
                    sourceType: ['album'],
                    success: (responent) => {
                        let videoFile = responent.tempFilePath;
                        uni.uploadFile({
                            url:this.config.fileUrl,
                            method:"POST",
                            header:{
                                'Authorization':'bearer '+ uni.getStorageSync('token')
                            },
                            filePath:videoFile,
                            name:'file',
                            success: (res) => {                    
                                // let videoUrls = JSON.parse(res.data) //微信和头条支持
                                let videoUrls = res.data //百度支持
                                this.imagesUrlPath = this.imagesUrlPath.concat(videoUrls.result.filePath);
                                this.src = videoUrls.result.filePath; //微信
                                if(this.src) {
                                    this.itemList = ['图片']
                                } else {
                                    this.itemList = ['图片','视频']
                                }
                                
                            }
                        })
                        // this.src = responent.tempFilePath;  //头条
                    }
                })
            },
            previewImage: function(e) {
                //预览图片
                var current = e.target.dataset.src
                uni.previewImage({
                    current: current,
                    urls: this.imageList
                })
            },
            delect(index){
                uni.showModal({
                    title: "提示",
                    content: "是否要删除该图片",
                    success: (res) => {
                        if (res.confirm) {
                            this.imageList.splice(index, 1)
                        }
                    }
                })
            },
            delectVideo(){
                uni.showModal({
                    title:"提示",
                    content:"是否要删除此视频",
                    success:(res) =>{
                        if(res.confirm){
                            this.src = ''
                        }
                    }
                })
            }
        }
    }
</script>

<style>
.burst-wrap{
    width: 100%;
    height: 100%;
}
/* .burst-wrap .burst-wrap-bg{
    position: relative;
    width: 100%;
    height: 320upx;
    background:linear-gradient(90deg,rgba(251,91,80,1) 0%,rgba(240,45,51,1) 100%);
    border-bottom-right-radius: 80upx;
    border-bottom-left-radius: 80upx;
} */
.burst-wrap .burst-wrap-bg>view{
    width: 90%;
    height: 100%;
    margin: 0 auto;
    position: absolute;
    top: 65upx;
    left: 0;
    right: 0;
}

.form-item{
    width: 100%;
}
.form-item textarea{
    display: block;
    height: 220upx;
    width: 100%;
    color: #AAAAAA;
    font-size: 28upx;
}
.uni-uploader__file,.uploader_video{
    position: relative;
    z-index: 1;
    width: 200upx;
    height: 200upx;
}
.uni-uploader__img {
    width: 200upx;
    height: 200upx;
}
.icon-cuo {
    position: absolute;
    right: 0;
    top: 5upx;
    background: linear-gradient(90deg,rgba(251,91,80,1) 0%,rgba(240,45,51,1) 100%);
    color: #FFFFFF;
    z-index: 999;
    border-top-right-radius: 20upx;
    border-bottom-left-radius: 20upx;
}
.video{
    width: 100%;
    height: 100%;
}

.login-input-box{
    position: relative;
    border-bottom: 1upx solid #EEEEEE;
}
.login-input-box .forget,.login-input-box .phone{
    position: absolute;
    top: 0;
    height: 100%;
    z-index: 100;
}
.login-input-box .phone{
    width: 100upx;
    left: 0;
    color: #666666;
    font-weight: bold;
}
.login-input-box .phone-input{
    padding-left: 100upx;
}
.address-wrap,.open-info{
    margin-top: 20upx;
}
.open-info>view:last-child{
    font-size: 28upx;
    color: #999999;
}
.address-wrap .address {
    background: #F2F2F2;
    border-radius: 40upx;
    padding: 0 20upx;
}
.user-set-btn{
    margin: 40upx;
    background: linear-gradient(90deg,rgba(251,91,80,1) 0%,rgba(240,45,51,1) 100%);
    color: #FFFFFF;
    text-align: center;
    height: 88upx;
    line-height: 88upx;
}
</style>

 

以上都是实现这个功能的所有代码。

版权声明:本文为Govern66原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Govern66/article/details/104290216

智能推荐

uniapp 分包--上传功能

一、问题 二、原因 三、解决 uniapp 分包 uni-app HBuilderX 工程与 vue-cli 工程相互转换 互换前,可根据 uniapp 官网提供的 快速上手 构建工程 四、完成之后结果...

微信小程序 纯代码实现 单图片上传栏(含 上传功能和编辑功能)部分代码

    具体效果图: xf_jiancha.wxss 图片上传框 样式 xf_jiancha.wxml  图片上传核心代码 xf_jiancha.js 核心代码 和 data数据 服务器 controller (node.js)          ...

uniapp上传图片和视频到OSS

  1.首先需要拿到formData里面的参数如下所示: 2.无需后台返回使用工具拿到以上参数: 下载应用服务器代码 将文件解压,并打开upload.js文件 修改upload.js中的配置信息。     accessId : 设置你的AccessKeyId。 accessKey : 设置你的AessKeySecret。 host: 格式为bucketname.end...

webuploader 实现图片批量上传功能附实例代码

1、导入资源 2、JSP代码 3、Js代码 注意: 4、controller代码...

原生JS实现ajax图片上传功能(后台java)

1.首先引入样式: 2.然后在页面中添加: 非表单提交,必须添加此参数 3.HTML: 4.JS部分 5.JAVA后台代码: 这里的fileToLocal方法是公司其他同事已经编写,个人觉得不太好,可以用自己的方法代替上传,还是写出具体方法的实现,如下:...

猜你喜欢

PAT 1036

题意: 给一组学生成绩,求最高分的女生和最低分的男生,并求该分差 注意点 1.若最高分或最低分有多个人,则输出absent和NA!...

实例总篇-界面设计-隐藏窗体

设计过程: 1)新建对话框应用程序,命名为CHideWnd,删除窗口内的所用控件。 2)在对话框的OnInitDialog中添加如下代码: 3)添加WM_TIMER的消息处理   4)在OnTimer函数中添加如下代码  效果展示: 无法展示,抱歉...

微信小程序云开发新手教程——数据库的增删改查

利用微信小程序云开发提供的数据库,可以对进行微信小程序的一些基本的数据管理,本片文章将从最基本的使用操作入手,介绍如何用云开发数据库API进行数据库的增删改查。 创建集合 如果你初次使用数据库,首先要创建一个数据库collection,才能进行数据的管理和调用。创建集合方法如下:打开微信开发者工具,点击云开发,在云开发控制台中点击数据库,在集合名称右侧的加号进行集合创建。 在实际使用中,具体要创建...

Git 服务器搭建及使用

多人合作开发的时候 常常会需要使用代码管理平台,保持代码一致和解决冲突。在工作中我使用过SVN和TFS,本文说明另外一种平台,Git,下面是基于Ubuntu环境安装并简单使用Git服务器。 确认安装git git --version可查看版本。 1.创建一个git用户 输入密码并确认密码。 如果是root用户,可直接切到该用户: 查看目录 2.初始化仓库 创建名为project1的空仓库。&nda...

学习springboot小笔记(二)--swagger2的介绍以及使用

1、swagger2的理解 引言:为什么有swagger2? 传统的项目文档都是自己手动写的文档,但是,软件是会更新变化的,文档的更新会导致一个API接口的信息不能够及时更新,导致信息流传不是很友好。Swaggers就是将注解写在对应的API方法上,当程序改变的时候,就会将对应的API改变(这个在网页的 XXXXX-swagger2-ui.html上面,那么前后端就可以根据这个进行交流就好了,不会...