index.vue 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <template>
  2. </template>
  3. <script setup>
  4. import { ref } from 'vue';
  5. import axios from 'axios';
  6. import { ElMessage } from 'element-plus';
  7. const uploadRef = ref(null);
  8. const fileList = ref([]); // 存储文件列表
  9. // 文件选择时触发
  10. const handleChange = (file, files) => {
  11. // 验证文件类型和大小
  12. const validTypes = ['image/jpeg', 'video/mp4'];
  13. const isTypeValid = validTypes.includes(file.raw.type);
  14. const isSizeValid = file.size / 1024 / 1024 < 100; // 限制100MB
  15. if (!isTypeValid) {
  16. ElMessage.error('仅支持 JPG/MP4 格式');
  17. uploadRef.value.remove(file); // 移除无效文件
  18. } else if (!isSizeValid) {
  19. ElMessage.error('文件大小超过100MB');
  20. uploadRef.value.remove(file);
  21. }
  22. };
  23. // 手动提交上传
  24. const submitUpload = () => {
  25. if (fileList.value.length === 0) {
  26. ElMessage.warning('请先选择文件');
  27. return;
  28. }
  29. const formData = new FormData();
  30. fileList.value.forEach(file => {
  31. formData.append('files', file.raw); // 添加所有文件[3,9](@ref)
  32. });
  33. // 添加额外参数(可选)
  34. formData.append('userId', '123');
  35. // 发送请求
  36. axios.post('https://api.example.com/upload', formData, {
  37. headers: { 'Content-Type': 'multipart/form-data' },
  38. onUploadProgress: (e) => {
  39. console.log(`进度: ${Math.round((e.loaded / e.total) * 100)}%`);
  40. }
  41. }).then(res => {
  42. ElMessage.success('上传成功');
  43. uploadRef.value.clearFiles(); // 清空文件列表[8](@ref)
  44. }).catch(err => {
  45. ElMessage.error('上传失败');
  46. });
  47. };
  48. </script>