• Axios 中的文件上传(Upload File)方法


    Axios 提供了多种上传文件(Upload File)的方法,适用于不同的上传场景。以下是其中几种常用的方法:

    1. 使用 FormData 对象
    
    • 1

    FormData是一个用于创建表单数据的 API,可用于发送包含文件和其他表单数据的multipart/form-data请求。这是处理文件上传的常用方法。通过FormData对象,可以将文件数据添加到表单中,然后使用 Axios 的post或put方法发送请求。

    示例

    const axios = require('axios');
    
    const fileInput = document.querySelector('#fileInput');
    const file = fileInput.files[0];
    
    const formData = new FormData();
    formData.append('file', file);
    
    axios.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(response => {
      console.log('上传成功', response.data);
    }).catch(error => {
      console.error('上传失败', error);
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    项目中使用

    onChange={async (info: any) => {
                    const formData = new FormData();
                    const fileList = info.fileList;
                    fileList.forEach((file: any) => {
                        formData.append("file", file.originFileObj);
                    });
                    localStorage.setItem('fileName', fileList[0].name)
                    axios.post('http://xxx.xxx.x.xx:8000/upload', formData,
                        {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        })
                        .then(res => {
                            if (res) {
    
                            }
                        })
                }}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    2. 使用 URL 参数

    除了使用FormData,你还可以通过在 URL 参数中指定文件名的方式上传文件。这种方法适用于后端期望文件名直接出现在 URL 中的情况。

    const axios = require('axios');
    
    const fileInput = document.querySelector('#fileInput');
    const file = fileInput.files[0];
    
    axios.post('/upload', file, {
      params: {
        fileName: file.name
      }
    }).then(response => {
      console.log('上传成功', response.data);
    }).catch(error => {
      console.error('上传失败', error);
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    3. 使用 Base64 编码

    这种方法将文件转换成 Base64 编码的字符串,然后通过普通的 JSON 格式发送给服务器。这种方式适用于较小的文件,因为 Base64 编码会增加数据大小。

    const axios = require('axios');
    
    const fileInput = document.querySelector('#fileInput');
    const file = fileInput.files[0];
    
    const reader = new FileReader();
    
    reader.onload = function(event) {
      const base64Data = event.target.result.split(',')[1];
    
      axios.post('/upload', {
        file: base64Data
      }).then(response => {
        console.log('上传成功', response.data);
      }).catch(error => {
        console.error('上传失败', error);
      });
    };
    
    reader.readAsDataURL(file);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    4.发送文件 Blob 对象

    可以通过 CreateObjectURL 把文件对象转成 Blob URL,然后作为 Axios 请求的数据发送。

    const file = document.getElementById('file').files[0];
    
    const blobUrl = URL.createObjectURL(file);
    
    axios.post('/upload', blobUrl, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }  
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    使用说明文档

    https://apifox.com/apiskills/axios-upload-file/

  • 相关阅读:
    k8s 容忍和污点
    二分图匹配(Hopcroft-Carp 的算法)
    uniapp—day02
    通过HTTP进行并发的数据抓取
    代码随想录算法训练营第五十五天|392. 判断子序列、115. 不同的子序列
    修改docker 版本的mysql 8.0 本机Navicat 连不上的问题
    MySQL高级(纯笔记,未整理)
    虹科活动 | 探索全新AR应用时代,虹科AR VIP研讨会广州场回顾!
    深入了解Golang:基本语法与核心特性解析
    Linux常用命令大全(非常全面)
  • 原文地址:https://blog.csdn.net/Maxueyingying/article/details/136685439