首页 > web前端 > js教程 > 正文

使用Axios发送multipart/mixed请求的教程

碧海醫心
发布: 2025-09-20 10:27:18
原创
719人浏览过

使用Axios发送multipart/mixed请求的教程

本教程详细探讨了如何在不同JavaScript环境中构建和发送multipart/mixed类型的POST请求,特别是区分了Node.js环境中使用form-data库的便捷方式,以及在浏览器环境中手动构造请求体的复杂但必要的实现方法。文章将涵盖XML片段和二进制文件混合传输的场景,并提供具体的代码示例和注意事项。

1. 理解 multipart/mixed 与 multipart/form-data

在web开发中,当我们通过http post请求上传数据时,常常会遇到multipart类型的content-type。其中,multipart/form-data是最常见的,通常用于表单提交,浏览器会自动处理边界字符串和各部分的头部信息。然而,某些特定的api(例如,旧版或专有协议)可能要求使用multipart/mixed类型,它提供了更大的灵活性,允许在单个请求体中混合不同类型的数据(如文本、xml、json、二进制文件等),并且需要手动管理边界字符串和各部分的content-disposition、content-type等头部。

本文的目标是构建一个multipart/mixed请求,其中包含一个XML片段和一个二进制文件,其结构如下:

--boundary-string
Content-Disposition: name="request_payload"
Content-Type: text/xml

<tsRequest>
  <!-- XML 内容 -->
</tsRequest>
--boundary-string
Content-Disposition: name="tableau_workbook"; filename="workbook-file-name"
Content-Type: application/octet-stream

--content-of-workbook-file--
--boundary-string--
登录后复制

2. 在 Node.js 环境中构建 multipart/mixed 请求

在Node.js环境中,可以使用form-data库来简化multipart请求的构建,即使是multipart/mixed类型也能灵活处理。该库允许我们手动指定每个部分的Content-Type,并能方便地获取请求所需的头部信息和边界字符串。

所需依赖:

{
  "dependencies": {
    "axios": "^1.3.4",
    "form-data": "^4.0.0"
  }
}
登录后复制

示例代码:

const FormData = require("form-data");
const Axios = require("axios");

// 假设 XML 片段和文件内容已准备好
const xmlString = `<tsRequest>
  <workbook name="workbook-name" showTabs="show-tabs-flag" thumbnailsUserId="user-luid">
    <connections>
    <connection serverAddress="server-address" serverPort="port-number">
    <connectionCredentials name="connection-username" password="connection-password"
          embed="embed-flag" />
    </connection>
    </connections>
    <project id="project-id"/>
  </workbook>
</tsRequest>`;
const fileContentArrayBuffer = new ArrayBuffer(1024); // 替换为实际的 ArrayBuffer 文件内容

// 创建 FormData 实例
const form = new FormData();

// 添加第一个部分:XML 片段
form.append("request_payload", xmlString, {
  contentType: "text/xml", // 明确指定 Content-Type
});

// 添加第二个部分:二进制文件
form.append("tableau_workbook", Buffer.from(fileContentArrayBuffer), { // 在 Node.js 中,Buffer 更常用
  filename: "workbook-file-name.twb", // 指定文件名
  contentType: "application/octet-stream", // 明确指定 Content-Type
});

// 创建 Axios 客户端
const axiosClient = Axios.create({
  baseURL: "https://your-api-base-url.com", // 替换为你的 API 基础 URL
});

// 发送 POST 请求
async function sendMultipartMixedRequest() {
  try {
    const response = await axiosClient.post("sites/:siteId/workbooks", form, {
      headers: {
        ...form.getHeaders(), // 获取 form-data 自动生成的头部,包括 Content-Type 和边界
        // 关键一步:覆盖 Content-Type 为 multipart/mixed 并使用 form-data 的边界
        "Content-Type": `multipart/mixed; boundary=${form.getBoundary()}`,
      },
    });
    console.log("请求成功:", response.data);
    return response.data;
  } catch (error) {
    console.error("发送请求失败:", error.response ? error.response.data : error.message);
    throw error;
  }
}

// 调用函数发送请求
// sendMultipartMixedRequest();
登录后复制

注意事项:

  • form-data库在append方法中允许通过第三个参数指定contentType和filename,这对于构建multipart/mixed至关重要。
  • form.getHeaders()会返回一个包含Content-Type(通常是multipart/form-data)和边界字符串的对象。
  • 为了实现multipart/mixed,我们手动覆盖了Content-Type,并利用form.getBoundary()来获取正确的边界字符串。
  • 在Node.js中,处理二进制数据时通常使用Buffer对象。

3. 在浏览器环境中构建 multipart/mixed 请求

浏览器环境中的FormData API主要用于构建multipart/form-data请求。它会自动处理边界和每个部分的头部。要实现multipart/mixed,特别是当需要精确控制每个部分的Content-Type和Content-Disposition时,我们通常需要手动构造请求体。这涉及到将所有部分(包括边界、头部和数据)拼接成一个Blob对象。

豆绘AI
豆绘AI

豆绘AI是国内领先的AI绘图与设计平台,支持照片、设计、绘画的一键生成。

豆绘AI 485
查看详情 豆绘AI

示例代码:

import axios from 'axios'; // 假设你已安装并导入 Axios

/**
 * 在浏览器环境中发送 multipart/mixed POST 请求
 * @param {string} xmlString - 要发送的 XML 片段字符串
 * @param {ArrayBuffer} fileArrayBuffer - 要发送的二进制文件内容的 ArrayBuffer
 * @param {string} endpointUrl - API 接口的 URL
 * @returns {Promise<any>} - Axios 响应数据
 */
async function sendMultipartMixedInBrowser(xmlString, fileArrayBuffer, endpointUrl) {
    // 1. 生成一个唯一的边界字符串
    // 推荐使用随机字符串,确保与请求体内容不冲突
    const boundaryString = `----WebKitFormBoundary${Math.random().toString(36).substring(2, 15)}`;

    // TextEncoder 用于将字符串转换为 Uint8Array,以便与二进制数据一起处理
    const encoder = new TextEncoder();

    // 存储所有请求体部分的数组
    const requestBodyParts = [];

    // --- 第一部分:XML 片段 ---
    requestBodyParts.push(encoder.encode(`--${boundaryString}\r\n`)); // 边界
    requestBodyParts.push(encoder.encode(`Content-Disposition: name="request_payload"\r\n`)); // 内容处置
    requestBodyParts.push(encoder.encode(`Content-Type: text/xml; charset=UTF-8\r\n\r\n`)); // 内容类型和空行
    requestBodyParts.push(encoder.encode(xmlString + '\r\n')); // XML 内容和结束换行

    // --- 第二部分:二进制文件内容 ---
    requestBodyParts.push(encoder.encode(`--${boundaryString}\r\n`)); // 边界
    requestBodyParts.push(encoder.encode(`Content-Disposition: name="tableau_workbook"; filename="workbook-file-name.twb"\r\n`)); // 内容处置(包含文件名)
    requestBodyParts.push(encoder.encode(`Content-Type: application/octet-stream\r\n\r\n`)); // 内容类型和空行
    requestBodyParts.push(fileArrayBuffer); // 直接添加 ArrayBuffer 形式的文件内容
    requestBodyParts.push(encoder.encode('\r\n')); // 结束换行

    // --- 最终边界 ---
    requestBodyParts.push(encoder.encode(`--${boundaryString}--\r\n`)); // 最终边界(注意末尾的两个短横线)

    // 2. 将所有部分组合成一个 Blob 对象
    // Blob 构造函数可以接受 DOMString, ArrayBuffer, ArrayBufferView, Blob, File 等类型
    const requestBodyBlob = new Blob(requestBodyParts, {
        type: `multipart/mixed; boundary=${boundaryString}` // 指定整个请求体的 Content-Type
    });

    // 3. 使用 Axios 发送请求
    try {
        const response = await axios.post(
            endpointUrl,
            requestBodyBlob, // 直接发送 Blob 对象作为请求体
            {
                headers: {
                    'Content-Type': `multipart/mixed; boundary=${boundaryString}`, // 再次设置 Content-Type 头部
                    // 可以在此处添加其他必要的头部,如认证信息
                    // 'Authorization': 'Bearer your_token'
                },
            }
        );
        console.log('请求成功:', response.data);
        return response.data;
    } catch (error) {
        console.error('发送请求失败:', error.response ? error.response.data : error.message);
        throw error;
    }
}

// 示例用法(在 React 组件或其他浏览器环境中)
// const myXmlData = '<tsRequest><workbook name="my-report">...</workbook></tsRequest>';
// const myFileData = new ArrayBuffer(1024); // 假设这是从文件读取的 ArrayBuffer
// // 或者从 File 对象获取 ArrayBuffer:
// // const fileInput = document.getElementById('fileInput');
// // const file = fileInput.files[0];
// // const reader = new FileReader();
// // reader.onload = (e) => {
// //   const fileArrayBuffer = e.target.result;
// //   sendMultipartMixedInBrowser(myXmlData, fileArrayBuffer, 'https://your-api-endpoint/sites/:siteId/workbooks');
// // };
// // reader.readAsArrayBuffer(file);

// sendMultipartMixedInBrowser(myXmlData, myFileData, 'https://your-api-endpoint/sites/:siteId/workbooks');
登录后复制

重要注意事项:

  • 边界字符串 (boundaryString): 必须是唯一的,且不能出现在请求体内的任何数据中。通常会生成一个随机字符串。
  • 行终止符 (\r\n): 严格按照multipart规范,各部分之间和头部与内容之间必须使用CRLF(回车换行,\r\n)。
  • 空行: 每个部分的头部与内容之间必须有一个空行(即\r\n\r\n)。
  • 最终边界: 请求体的末尾必须是边界字符串后跟两个短横线(--${boundaryString}--\r\n)。
  • Blob 对象: 浏览器中,Blob是发送复杂二进制或混合数据类型请求体的理想选择。
  • TextEncoder: 用于将 JavaScript 字符串编码为Uint8Array,以便与二进制数据(ArrayBuffer)一起放入Blob中。
  • Content-Type 头部: 务必在 Axios 请求的headers中设置正确的Content-Type,包括边界字符串。

4. 总结

无论是Node.js还是浏览器环境,构建multipart/mixed请求都需要对HTTP协议的multipart规范有深入理解。

  • Node.js 环境:form-data库极大地简化了这一过程,通过其append方法和getHeaders()、getBoundary()方法,可以方便地构造请求体和头部。
  • 浏览器环境:由于浏览器原生FormData的限制,通常需要手动拼接字符串和二进制数据,然后将其封装成一个Blob对象,并确保Content-Type头部设置正确。

在实际开发中,应根据目标API的要求和所处的运行环境选择合适的实现方式。手动构造multipart/mixed虽然代码量稍大,但提供了最高的灵活性和控制力。

以上就是使用Axios发送multipart/mixed请求的教程的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号