vue实现上传视频
使用 <input type="file"> 实现基础上传
通过 HTML 原生文件选择控件获取视频文件,结合 Vue 处理上传逻辑。
<template>
<div>
<input type="file" accept="video/*" @change="handleFileUpload" />
<button @click="uploadVideo">上传</button>
</div>
</template>
<script>
export default {
data() {
return {
videoFile: null
};
},
methods: {
handleFileUpload(event) {
this.videoFile = event.target.files[0];
},
uploadVideo() {
if (!this.videoFile) return;
const formData = new FormData();
formData.append('video', this.videoFile);
// 替换为实际 API 地址
axios.post('/api/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
}).then(response => {
console.log('上传成功', response);
}).catch(error => {
console.error('上传失败', error);
});
}
}
};
</script>
使用第三方库(如 vue-dropzone)增强功能
集成 vue-dropzone 实现拖拽上传、进度显示等高级功能。
安装依赖:

npm install vue2-dropzone
示例代码:
<template>
<vue-dropzone
ref="dropzone"
id="video-uploader"
:options="dropzoneOptions"
@vdropzone-success="onUploadSuccess"
></vue-dropzone>
</template>
<script>
import vue2Dropzone from 'vue2-dropzone';
import 'vue2-dropzone/dist/vue2Dropzone.min.css';
export default {
components: { vueDropzone: vue2Dropzone },
data() {
return {
dropzoneOptions: {
url: '/api/upload',
acceptedFiles: 'video/*',
maxFilesize: 500, // 限制文件大小(MB)
addRemoveLinks: true,
uploadMultiple: false
}
};
},
methods: {
onUploadSuccess(file, response) {
console.log('文件上传成功', response);
}
}
};
</script>
显示上传进度
通过 Axios 或原生 XMLHttpRequest 监听上传进度,实时更新 UI。

<template>
<div>
<input type="file" @change="handleFileUpload" />
<progress :value="uploadProgress" max="100"></progress>
</div>
</template>
<script>
export default {
data() {
return {
uploadProgress: 0
};
},
methods: {
handleFileUpload(event) {
const file = event.target.files[0];
const formData = new FormData();
formData.append('video', file);
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (e) => {
this.uploadProgress = Math.round((e.loaded / e.total) * 100);
});
xhr.open('POST', '/api/upload', true);
xhr.send(formData);
}
}
};
</script>
后端处理建议
需确保后端 API 支持以下功能:
- 接收
multipart/form-data格式数据。 - 对视频文件进行大小、类型校验(如仅允许
.mp4、.mov)。 - 返回上传结果(成功/失败)及存储路径。
示例 Node.js 代码片段(使用 Express 和 multer):
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/api/upload', upload.single('video'), (req, res) => {
if (!req.file) return res.status(400).send('未上传文件');
res.json({ path: req.file.path });
});
安全性注意事项
- 前端限制文件类型和大小,但需在后端重复验证。
- 对上传的文件进行病毒扫描(如集成 ClamAV)。
- 避免直接返回敏感文件路径,建议返回经过处理的访问 URL。
通过以上方法,可灵活实现 Vue 中的视频上传功能,并根据需求扩展进度显示、拖拽上传等特性。






