uniapp上传图片和上传视频的实现方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

uniapp上传图片和上传视频的实现方法

廖若星辰LTY   2023-02-03 我要评论

基于 uniapp 的应用上传图片/视频 资源的实现:

功能涉及的主要 uniapp API 如下:

1.选择图片uni.chooseImage(OBJECT) | uni-app官网

2.选择视频uni.chooseVideo(OBJECT) | uni-app官网

3.上传文件uni.uploadFile(OBJECT) | uni-app官网

下面分别贴出示例代码:

上传图片

        // 上传图片
		async chooseImages() {
			uni.showLoading({
				mask: true,
				title: '上传中...'
			})
			// uploadFile 存储需要上传的文件
			let uploadFile = ''
			// 1.选择图片(这里只能单选)
			const res = await uni.chooseImage({
				count: 1,	// 最多可以选择的图片张数,默认9
				// sizeType: ['compressed'],		// original 原图,compressed 压缩图,默认二者都有
				sourceType: ['album'],		// album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
			});
			// console.log('res:', res);
			if(res.length < 2) {		// 小于2则没有选择图片
				uni.hideLoading()
				return
			}
			uploadFile = res[1].tempFilePaths[0];	// 拿到选择的文件
			var that1 = this;
			// 2.将选择的图片上传到目标服务器
			const arr = await uni.uploadFile({
				// 需要上传的地址
				url: that1.vuex_uploadAction,
				// filePath  需要上传的文件
				filePath: uploadFile,
				name: 'file',
				timeout: 2000,		// 超时时间
				header: {		// HTTP 请求 Header, header 中不能设置 Referer。
					token: that1.vuex_token		// 挂载请求头为用户的 token
				},
			});
			// console.log(arr);
			let data = JSON.parse(arr[1].data)
			console.log('data:', data);
			if(data.code !== 1) {	// 图片上传失败了
				uni.hideLoading()
				that1.$u.toast(data.msg)
				return
			}
			// 上传成功(把上传成功后的文件路径 push 到页面需要显示的图片数据列表中)
			that1.fileList.push(data.data.fullurl)
			that1.formData.photo_url.push(data.data.url)
			// console.log(that1.fileList);
			uni.hideLoading()
		},

注:示例代码已封装为一个方法,可直接调用,需要自定义之处可自行参照 API 文档修改,比如从相册选图还是打开相机拍照、可上传的图片数量等

上传视频

        // 上传视频
		async chooseVideo() {
			uni.showLoading({
				mask: true,
				title: '上传中...'
			})
			// uploadFile 存储需要上传的文件
			let uploadFile = ''
			// 1.选择要上传的视频
			const res = await uni.chooseVideo({
				maxDuration: 60,		// 拍摄视频最长拍摄时间,单位秒。最长支持 60 秒。
				sourceType: ['album'],		// album 从相册选视频,camera 使用相机拍摄,默认为:['album', 'camera']
			});
			uploadFile = res[1].tempFilePath;
			// console.log(uploadFile);
			var that2 = this;
			// 2.上传所选视频到服务器
			const arr = await uni.uploadFile({
				// 需要上传的地址
				url: that2.vuex_uploadAction,
				// filePath  需要上传的文件
				filePath: uploadFile,
				name: 'file',
				header: {
					token: that2.vuex_token		// 挂载请求头为用户的 token
				},
			});
			let data = JSON.parse(arr[1].data)
			console.log('data:', data);
			if(data.code !== 1) {		// 视频上传失败了
				uni.hideLoading()
				that1.$u.toast(data.msg)
				return
			}
			// 上传成功(把上传成功后的文件路径 push 到页面需要显示的视频数据列表中)
			that2.uploadVideoUrl = data.data.fullurl
			that2.formData.video_url = data.data.url
			uni.hideLoading()
		}

扩展

uniapp 还整合提供了上传媒体文件(图片/视频)的 API: uni.chooseMedia 可用于上传图片和视频。若有兴趣可自行打开链接测试使用。

补充:上传文件实例

上传文件使用的LFile 这个插件 https://ext.dcloud.net.cn/plugin?id=4109

根据官网案例来

 
		 //上传附件
			uploadFile() {
				const that = this;
				if(that.imgUploadList.length >= 9){
					this.$mHelper.toast('最多上传9张')
					return;
				}
				that.$refs.lFile.upload({
						// #ifdef APP-PLUS
						currentWebview: that.$mp.page.$getAppWebview(),
						// #endif
						url: 'xxxxxx', //你的上传附件接口地址
						name: 'file'
						},
					});
			},
         //上传成功
			upSuccess(res) {
				let url = res.root.url;
				let name = res.root.originalName;
				let fileType = this.isFileType(res.root.type);
				let size = res.root.size;
				if(fileType == 'image'){
					this.imgUploadList.push({url,name,fileType,size});
				}else{
					this.fileUploadList.push({url,name,fileType,size})
				}
			},
         //根据文件后缀名来判断,展示对应的图标
        isImage(type){
				return ['png','jpg','jpeg','gif','svg'].includes(type.toLowerCase());
			},
			isDocx(type){
				return ['doc','docx'].includes(type.toLowerCase());
			},
			isXsls(type){
				return ['xsls','xsl'].includes(type.toLowerCase());
			},
			isText(type){
				return ['text','txt'].includes(type.toLowerCase());
			},
			isFileType(type){
				if(this.isImage(type)) return 'image';
				if(this.isXsls(type)) return 'excel';
				if(type == 'pdf') return 'pdf';
				if(this.isDocx(type)) return 'word';
				if(this.isText(type)) return "text";
				// return "#icon-file-b--6";
			},
           //文件预览
			previewFile(item){
				uni.downloadFile({
					url: item.url,
					success: (res) => {
						let filePath = res.tempFilePath;
						uni.openDocument({
							filePath: filePath,
							success: (res) => {
								console.log('打开文档成功');
							}
						})
					}
				})
			},

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们