如何在浏览器中用JavaScript发送multipart/related类型POST请求?
我明白你的痛点——axios确实没有原生支持multipart/related类型,这在对接Google Drive这类要求该格式的API时确实挺麻烦的。不过有几个靠谱的变通方案,我给你详细说说:
multipart/related的核心是用自定义边界分隔多个请求部分(比如元数据和文件内容),每个部分有自己的Content-Type。我们可以手动拼接这些部分,再用axios发送。
举个Node.js环境下的示例:
const axios = require('axios'); const fs = require('fs'); // 1. 定义唯一的边界字符串(避免和内容冲突) const boundary = '----GoogleDriveMultipartBoundary12345'; // 2. 准备文件元数据(对应Google Drive要求的JSON结构) const fileMetadata = JSON.stringify({ name: '我的测试文件.txt', parents: ['你的文件夹ID'] // 可选,指定上传到哪个文件夹 }); // 3. 读取要上传的文件内容 const fileBuffer = fs.readFileSync('./test.txt'); // 4. 手动拼接multipart/related请求体 const multipartBody = Buffer.concat([ Buffer.from(`--${boundary}\r\n`), Buffer.from('Content-Type: application/json; charset=UTF-8\r\n\r\n'), Buffer.from(fileMetadata + '\r\n'), Buffer.from(`--${boundary}\r\n`), Buffer.from('Content-Type: text/plain\r\n\r\n'), // 替换为你的文件MIME类型 fileBuffer, Buffer.from(`\r\n--${boundary}--\r\n`) ]); // 5. 用axios发送请求 axios.post( 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', multipartBody, { headers: { 'Authorization': `Bearer ${你的访问令牌}`, 'Content-Type': `multipart/related; boundary=${boundary}` } } ) .then(res => console.log('上传成功!文件ID:', res.data.id)) .catch(err => console.error('上传失败:', err.response?.data || err.message));
⚠️ 注意:如果上传大文件,建议用流(fs.createReadStream)来拼接请求体,避免内存溢出。
方案2:使用官方Google Drive客户端库(最省心)
其实不用自己折腾请求格式,Google官方提供的googleapis库已经完全封装了multipart上传的逻辑,兼容性和稳定性都拉满。
步骤很简单:
- 安装依赖:
npm install googleapis
- 写上传代码:
const { google } = require('googleapis'); const fs = require('fs'); // 初始化Drive客户端(传入你的访问令牌) const drive = google.drive({ version: 'v3', auth: '你的访问令牌' }); // 上传文件 drive.files.create({ // 文件元数据 resource: { name: '我的测试文件.txt', parents: ['你的文件夹ID'] }, // 文件内容 media: { mimeType: 'text/plain', body: fs.createReadStream('./test.txt') // 支持流,适合大文件 }, // 指定返回的字段(这里只返回文件ID) fields: 'id' }) .then(res => console.log('上传成功!文件ID:', res.data.id)) .catch(err => console.error('上传失败:', err.message));
这个方案我最推荐——不用关心底层的multipart格式,官方库会自动处理,还支持分块上传、断点续传等高级功能。
方案3:改用Fetch API(原生支持自定义请求体)
如果不想用axios,浏览器或Node.js的Fetch API可以直接发送自定义的请求体,逻辑和手动构造axios请求类似:
const fs = require('fs'); // Node.js环境,浏览器直接用File对象 const boundary = '----GoogleDriveMultipartBoundary12345'; const fileMetadata = JSON.stringify({ name: '我的测试文件.txt' }); const fileBuffer = fs.readFileSync('./test.txt'); // 构造Blob形式的请求体 const formData = new Blob([ `--${boundary}\r\n`, 'Content-Type: application/json; charset=UTF-8\r\n\r\n', fileMetadata + '\r\n', `--${boundary}\r\n`, 'Content-Type: text/plain\r\n\r\n', fileBuffer, `\r\n--${boundary}--\r\n` ]); // 发送请求 fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', { method: 'POST', headers: { 'Authorization': `Bearer ${你的访问令牌}`, 'Content-Type': `multipart/related; boundary=${boundary}` }, body: formData }) .then(res => res.json()) .then(data => console.log('上传成功!文件ID:', data.id)) .catch(err => console.error('上传失败:', err.message));
内容的提问来源于stack exchange,提问作者jimijuu omastar
相关产品推荐
相关产品推荐

