index.vue 1.5 KB

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