uniapp试视频上传
时间: 2025-02-19 12:25:54 浏览: 59
### UniApp 中实现视频上传功能
在UniApp项目中实现视频上传功能涉及前端页面设计以及与服务器交互的部分。下面提供了一个简单的实例来展示如何完成这一操作。
#### 前端部分:创建用于选择和预览视频的界面组件
通过`<video>`标签可以方便地嵌入视频播放器,并允许用户选取本地文件作为待上传的内容。为了简化流程,这里采用`uni.chooseVideo()` API 来让用户挑选设备中的媒体资源[^1]。
```html
<!-- video-upload.vue -->
<template>
<view class="container">
<!-- 显示已选中的视频缩略图 -->
<image v-if="tempFilePath" :src="tempFilePath" mode="aspectFill"></image>
<!-- 添加按钮触发视频选择 -->
<button type="primary" @click="chooseVideo">选择视频</button>
<!-- 提交按钮 -->
<button type="warn" @click="uploadVideo" :disabled="!tempFilePath">上传视频</button>
</view>
</template>
<script>
export default {
data() {
return {
tempFilePath: ''
}
},
methods: {
chooseVideo() {
uni.chooseVideo({
sourceType: ['album', 'camera'], // 可以从相册或相机选择
maxDuration: 60, // 设置最大录制时间为60秒
success(res) {
this.tempFilePath = res.tempFilePath;
}.bind(this),
fail(err){
console.error('Failed to select video:', err);
}
});
},
uploadVideo(){
const filePath = this.tempFilePath;
if (!filePath) {return;}
uni.uploadFile({
url: 'https://example.com/upload', // 替换成实际的服务端地址
filePath,
name: 'file',
formData: {'user': 'test'}, // 额外表单数据可在此处添加
success(uploadRes) {
let result = JSON.parse(uploadRes.data);
if (result.code === 200) {
uni.showToast({title:'上传成功'});
} else {
uni.showModal({content:`上传失败:${result.msg}`, showCancel:false});
}
console.log(`Server response`, result);
},
fail(error){
console.error('Upload failed:', error);
}
})
}
}
}
</script>
```
上述代码片段展示了怎样构建一个基本的选择和上传视频的功能模块,在此过程中使用到了两个重要的API函数——`uni.chooseVideo()` 和 `uni.uploadFile()` 。前者负责打开系统的多媒体库供用户选择要上传的视频;后者则用来处理具体的HTTP请求并将选定好的文件发送给指定的目标URL。
需要注意的是,服务端接收逻辑未在此详述,请自行搭建相应的接口以便能够正确解析来自客户端提交的数据流并保存到合适的位置上。
阅读全文
相关推荐


















