vue实现视频上传
Vue 实现视频上传的方法
使用原生 input 元素和 FormData
在 Vue 中可以通过原生 input 元素结合 FormData 实现视频上传功能。创建一个文件选择输入框,监听文件变化事件,将选中的视频文件通过 FormData 发送到服务器。
<template>
<div>
<input type="file" accept="video/*" @change="handleFileChange" />
<button @click="uploadVideo">上传视频</button>
</div>
</template>
<script>
export default {
data() {
return {
selectedFile: null
};
},
methods: {
handleFileChange(event) {
this.selectedFile = event.target.files[0];
},
uploadVideo() {
if (!this.selectedFile) return;
const formData = new FormData();
formData.append('video', this.selectedFile);
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log('上传成功', response.data);
}).catch(error => {
console.error('上传失败', error);
});
}
}
};
</script>
使用第三方上传组件
许多第三方 UI 库提供了更完善的上传组件,如 Element UI 的 el-upload。这些组件通常内置了进度显示、文件类型限制等功能。
<template>
<el-upload
action="/api/upload"
:auto-upload="false"
:on-change="handleChange"
:before-upload="beforeUpload"
:file-list="fileList"
accept="video/*"
>
<el-button type="primary">选择视频</el-button>
</el-upload>
</template>
<script>
export default {
data() {
return {
fileList: []
};
},
methods: {
handleChange(file, fileList) {
this.fileList = fileList;
},
beforeUpload(file) {
const isVideo = file.type.includes('video');
if (!isVideo) {
this.$message.error('只能上传视频文件');
return false;
}
return true;
}
}
};
</script>
分片上传大视频文件
对于大视频文件,可以采用分片上传的方式,将文件分割成多个小块分别上传,提高上传成功率。
async function uploadLargeFile(file) {
const chunkSize = 5 * 1024 * 1024; // 5MB
const totalChunks = Math.ceil(file.size / chunkSize);
for (let i = 0; i < totalChunks; i++) {
const start = i * chunkSize;
const end = Math.min(start + chunkSize, file.size);
const chunk = file.slice(start, end);
const formData = new FormData();
formData.append('chunk', chunk);
formData.append('chunkIndex', i);
formData.append('totalChunks', totalChunks);
formData.append('filename', file.name);
await axios.post('/api/upload-chunk', formData);
}
await axios.post('/api/merge-chunks', { filename: file.name });
}
显示上传进度
通过监听 XMLHttpRequest 的 upload.onprogress 事件或 axios 的 onUploadProgress 配置项,可以实时显示上传进度。
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
console.log(`${percentCompleted}%`);
}
})
视频预览功能
在上传前,可以通过 URL.createObjectURL() 方法生成视频的临时 URL,实现本地预览功能。
function previewVideo(file) {
const videoUrl = URL.createObjectURL(file);
const videoElement = document.createElement('video');
videoElement.src = videoUrl;
videoElement.controls = true;
document.body.appendChild(videoElement);
}
以上方法涵盖了从基础上传到高级功能的实现,可以根据项目需求选择合适的方案。对于生产环境,建议结合后端验证、文件大小限制、格式检查等安全措施。







