| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- <template>
- <div>
- </div>
- </template>
- <script setup>
- import { ref } from 'vue';
- import axios from 'axios';
- import { ElMessage } from 'element-plus';
- const uploadRef = ref(null);
- const fileList = ref([]); // 存储文件列表
- // 文件选择时触发
- const handleChange = (file, files) => {
- // 验证文件类型和大小
- const validTypes = ['image/jpeg', 'video/mp4'];
- const isTypeValid = validTypes.includes(file.raw.type);
- const isSizeValid = file.size / 1024 / 1024 < 100; // 限制100MB
- if (!isTypeValid) {
- ElMessage.error('仅支持 JPG/MP4 格式');
- uploadRef.value.remove(file); // 移除无效文件
- } else if (!isSizeValid) {
- ElMessage.error('文件大小超过100MB');
- uploadRef.value.remove(file);
- }
- };
- // 手动提交上传
- const submitUpload = () => {
- if (fileList.value.length === 0) {
- ElMessage.warning('请先选择文件');
- return;
- }
- const formData = new FormData();
- fileList.value.forEach(file => {
- formData.append('files', file.raw); // 添加所有文件[3,9](@ref)
- });
- // 添加额外参数(可选)
- formData.append('userId', '123');
- // 发送请求
- axios.post('https://api.example.com/upload', formData, {
- headers: { 'Content-Type': 'multipart/form-data' },
- onUploadProgress: (e) => {
- console.log(`进度: ${Math.round((e.loaded / e.total) * 100)}%`);
- }
- }).then(res => {
- ElMessage.success('上传成功');
- uploadRef.value.clearFiles(); // 清空文件列表[8](@ref)
- }).catch(err => {
- ElMessage.error('上传失败');
- });
- };
- </script>
|