当前位置: 首页 > news >正文

upload文件上传

<template><div class="upload-container"><!-- 文件选择 --><inputtype="file"accept="video/*"@change="handleFileChange"ref="fileInput"/><!-- 上传按钮 --><button@click="startUpload":disabled="!file || isUploading">{{ isUploading ? `上传中... ${progress}%` : '上传视频' }}</button><!-- 进度条 --><div v-if="isUploading" class="progress-bar"><div class="progress" :style="{ width: progress + '%' }"></div></div><!-- 错误提示 --><div v-if="error" class="error">{{ error }}</div><!-- 视频预览 --><videov-if="previewUrl":src="previewUrl"controlsclass="preview"></video></div>
</template>
<script>
import axios from 'axios';
export default {name: 'Upload',data() {return {file: undefined,previewUrl: undefined,isUploading:false,progress: 0,error: undefined}},methods: {handleFileChange(e) {const selectedFile = e.target.files[0];if (!selectedFile) return;// 验证文件类型if (!selectedFile.type.startsWith('video/')) {this.error = '请选择视频文件!';return;}// 验证文件大小(例如限制100MB)const MAX_SIZE = 100 * 1024 * 1024; // 100MBif (selectedFile.size > MAX_SIZE) {this.error = '文件大小不能超过100MB!';return;}this.file = selectedFile;this.previewUrl = URL.createObjectURL(selectedFile);this.error = ''; // 清除之前的错误},async startUpload() {if (!this.file) return;this.isUploading = true;this.progress = 0;this.error = '';const formData = new FormData();formData.append('file', this.file); // 字段名需与后端一致try {const response = await axios.post('http://192.168.8.172:8077/common/upload',formData,{headers: {'Content-Type': 'multipart/form-data', // 必须设置'token': localStorage.getItem("usertoken")},onUploadProgress: (progressEvent) => {// 计算上传进度this.progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);},timeout: 300000, // 5分钟超时});console.log('上传成功:', response.data);alert('视频上传成功!');} catch (err) {this.handleUploadError(err);} finally {this.isUploading = false;}},// 错误处理handleUploadError(err) {if (err.code === 'ECONNABORTED') {this.error = '上传超时,请检查网络或稍后重试';} else if (err.response) {// 后端返回的错误this.error = err.response.data.message || `上传失败: ${err.response.status}`;} else {this.error = '上传失败,请检查网络连接';}console.error('上传错误:', err);}}}
</script>
<style scoped>
.upload-container {max-width: 500px;margin: 0 auto;padding: 20px;font-family: Arial, sans-serif;
}input[type="file"] {margin-bottom: 15px;display: block;
}button {background-color: #4CAF50;color: white;padding: 10px 15px;border: none;border-radius: 4px;cursor: pointer;font-size: 16px;
}button:disabled {background-color: #cccccc;cursor: not-allowed;
}.progress-bar {width: 100%;height: 10px;background-color: #f1f1f1;margin: 15px 0;border-radius: 5px;overflow: hidden;
}.progress {height: 100%;background-color: #4CAF50;transition: width 0.3s;
}.error {color: #ff0000;margin-top: 10px;
}.preview {width: 100%;max-height: 300px;margin-top: 20px;border: 1px solid #ddd;border-radius: 4px;
}
</style>

以上为vue2代码

<template><div class="upload-container"><!-- 文件选择 --><inputtype="file"accept="video/*"@change="handleFileChange"ref="fileInput"/><!-- 上传按钮 --><button@click="startUpload":disabled="!file || isUploading">{{ isUploading ? `上传中... ${progress}%` : '上传视频' }}</button><!-- 进度条 --><div v-if="isUploading" class="progress-bar"><div class="progress" :style="{ width: progress + '%' }"></div></div><!-- 错误提示 --><div v-if="error" class="error">{{ error }}</div><!-- 视频预览 --><videov-if="previewUrl":src="previewUrl"controlsclass="preview"></video></div></template><script setup>import { ref } from 'vue';import axios from 'axios';const fileInput = ref(null);const file = ref(null);const previewUrl = ref('');const isUploading = ref(false);const progress = ref(0);const error = ref('');// 选择文件const handleFileChange = (e) => {const selectedFile = e.target.files[0];if (!selectedFile) return;// 验证文件类型if (!selectedFile.type.startsWith('video/')) {error.value = '请选择视频文件!';return;}// 验证文件大小(例如限制100MB)const MAX_SIZE = 100 * 1024 * 1024; // 100MBif (selectedFile.size > MAX_SIZE) {error.value = '文件大小不能超过100MB!';return;}file.value = selectedFile;previewUrl.value = URL.createObjectURL(selectedFile);error.value = ''; // 清除之前的错误};// 开始上传const startUpload = async () => {if (!file.value) return;isUploading.value = true;progress.value = 0;error.value = '';const formData = new FormData();formData.append('file', file.value); // 字段名需与后端一致try {const response = await axios.post('http://localhost:8077/common/upload',formData,{headers: {'Content-Type': 'multipart/form-data', // 必须设置},onUploadProgress: (progressEvent) => {// 计算上传进度progress.value = Math.round((progressEvent.loaded / progressEvent.total) * 100);},timeout: 300000, // 5分钟超时});console.log('上传成功:', response.data);alert('视频上传成功!');} catch (err) {handleUploadError(err);} finally {isUploading.value = false;}};// 错误处理const handleUploadError = (err) => {if (err.code === 'ECONNABORTED') {error.value = '上传超时,请检查网络或稍后重试';} else if (err.response) {// 后端返回的错误error.value = err.response.data.message || `上传失败: ${err.response.status}`;} else {error.value = '上传失败,请检查网络连接';}console.error('上传错误:', err);};</script><style scoped>.upload-container {max-width: 500px;margin: 0 auto;padding: 20px;font-family: Arial, sans-serif;}input[type="file"] {margin-bottom: 15px;display: block;}button {background-color: #4CAF50;color: white;padding: 10px 15px;border: none;border-radius: 4px;cursor: pointer;font-size: 16px;}button:disabled {background-color: #cccccc;cursor: not-allowed;}.progress-bar {width: 100%;height: 10px;background-color: #f1f1f1;margin: 15px 0;border-radius: 5px;overflow: hidden;}.progress {height: 100%;background-color: #4CAF50;transition: width 0.3s;}.error {color: #ff0000;margin-top: 10px;}.preview {width: 100%;max-height: 300px;margin-top: 20px;border: 1px solid #ddd;border-radius: 4px;}</style>

以上为vue3代码

相关文章:

  • MySQL 的锁机制
  • Webug4.0靶场通关笔记24- 第29关Webshell爆破
  • Linux 大于2T磁盘分区
  • opencv中的图像特征提取
  • RK3588 Ubuntu安装Qt6
  • 从代码学习深度学习 - 区域卷积神经网络(R-CNN)系列 PyTorch版
  • levelDB的数据查看(非常详细)
  • 【面板数据】各省双向FDI协调发展水平数据集(2005-2022年)
  • 并发 vs 并行编程详解
  • el-form的label星号位置如何修改
  • Vue3 路由配置与跳转传参完整指南
  • MySQL主从同步(主从复制)
  • RDD行动算子案例
  • 论文分享➲ ICLR2025 Oral | Scaling and evaluating sparse autoencoders
  • 使用 Spring 和 Redis 创建处理敏感数据的服务
  • 剪映学习03
  • 常见图像融合算法(图像泊松融合)
  • neo4j图数据库基本概念和向量使用
  • python小区物业管理系统-小区物业报修系统
  • Missashe高数强化学习笔记(随时更新)
  • 道指跌逾100点,特斯拉涨近5%
  • 湖南省职业病防治院通报3岁女童确诊“铊中毒”:去年病例,编辑误写为“近日”
  • 蔡达峰:推动食品安全法全面有效实施,为维护人民群众身体健康提供有力法治保障
  • 复旦发文缅怀文科杰出教授裘锡圭:曾提出治学需具备三种精神
  • 新华每日电讯:给“男性妇科病论文”开一剂复方药
  • 上海发布预付卡消费“10点提示”:警惕“甩锅闭店”套路