如何用浏览器Fetch API发起multipart/related请求上传JSON附件?
核心结论
- 目前浏览器没有提供类似FormData的原生标准化multipart/related构造API,FormData默认生成的multipart/form-data请求体,其头部格式、内容约定和multipart/related存在差异,无法直接替换使用。
- 可以基于Blob/File API封装接近FormData易用性的构造器,无需手动硬拼二进制内容即可生成符合规范的请求体,完全适配Fetch API的发送要求。
可复用的构造器实现
以下封装类和原生FormData的调用逻辑一致,支持添加JSON主数据、多份附件文件,全程用二进制块拼接避免字符串编码错误:
class MultipartRelatedBuilder { constructor() { // 生成高随机性的boundary,避免和请求内容冲突 this.boundary = `----${crypto.randomUUID().replace(/-/g, '')}${Date.now().toString(16)}`; this.parts = []; } /** * 添加JSON格式的主数据部分 * @param {object} data 需要序列化的JSON对象 */ addJsonPart(data) { const jsonContent = JSON.stringify(data); const part = new Blob([ `Content-Type: application/json\r\n\r\n`, jsonContent, `\r\n` ]); this.parts.push(part); } /** * 添加文件附件部分 * @param {File|Blob} file 待上传的文件对象 * @param {string} [filename] 自定义文件名 */ addFilePart(file, filename = file.name) { const partHeader = [ `Content-Disposition: attachment; filename="${encodeURIComponent(filename)}"`, `Content-Type: ${file.type}`, ``, `` ].join('\r\n'); const part = new Blob([partHeader, file, `\r\n`]); this.parts.push(part); } /** * 生成最终可直接作为Fetch body的Blob对象 * @returns {Blob} 符合multipart/related规范的请求体 */ getBlob() { const partDelimiter = `--${this.boundary}\r\n`; const closingDelimiter = `--${this.boundary}--`; const chunkList = []; // 按顺序拼接所有部分 this.parts.forEach(part => { chunkList.push(new Blob([partDelimiter, part])); }); chunkList.push(new Blob([closingDelimiter])); // 将自定义boundary直接写入Blob的类型信息,浏览器会自动用这个值作为Content-Type请求头 return new Blob(chunkList, { type: `multipart/related; boundary="${this.boundary}"` }); } }
Fetch请求调用示例
对应参考的CouchDB上传场景,直接按顺序调用构造器方法生成请求体即可:
// 初始化构造器 const relatedBuilder = new MultipartRelatedBuilder(); // 添加文档元数据JSON部分 const docMeta = { "_attachments": { "recipe.txt": { "content_type": "text/plain", "digest": "md5-R5CrCb6fX10Y46AqtNn0oQ==", "follows": true, "length": 87, "revpos": 7 } }, "_id": "SpaghettiWithMeatballs", "_rev": "7-474f12eb068c717243487a9505f6123b", "_revisions": { "ids": [ "474f12eb068c717243487a9505f6123b", "5949cfcd437e3ee22d2d98a26d1a83bf" ], "start": 7 }, "description": "An Italian-American delicious dish", "ingredients": ["spaghetti", "tomato sauce", "meatballs", "love"], "name": "Spaghetti with meatballs" }; relatedBuilder.addJsonPart(docMeta); // 构造附件文件 const recipeContent = `1. Cook spaghetti 2. Cook meetballs 3. Mix them 4. Add tomato sauce 5. ... 6. PROFIT!`; const recipeFile = new File([recipeContent], "recipe.txt", { type: "text/plain" }); relatedBuilder.addFilePart(recipeFile); // 发送PUT请求 fetch('/target/SpaghettiWithMeatballs?new_edits=false', { method: 'PUT', headers: { 'Accept': 'application/json' // 禁止手动设置Content-Type! }, body: relatedBuilder.getBlob() });
必须注意的实现细节
- 不要在请求头里手动覆盖Content-Type配置:我们在构造Blob的时候已经把和内部分隔符匹配的boundary写到了Blob的类型信息里,如果在headers里手动写
Content-Type: multipart/related,会覆盖掉Blob自带的带boundary的完整类型,导致请求头里没有正确的boundary参数,服务端无法解析分隔符。只要不在headers里设置Content-Type,Fetch会自动读取Blob的类型信息作为请求头,完全匹配我们拼接的内容。 - 所有块的分隔符必须严格使用CRLF(
\r\n)换行,不能用普通LF(\n)换行,否则会违反multipart规范,导致服务端无法解析。 - 全程使用Blob/File API拼接内容,不要直接用字符串拼接请求体:字符串处理二进制文件时会出现编码偏差,尤其针对图片、压缩包等非文本类型的附件,会直接导致文件损坏。
- 多附件场景只需要循环调用
addFilePart方法传入不同的File对象即可,无需调整其他逻辑。
内容的提问来源于stack exchange,提问作者Anurag Vohra
相关产品推荐
相关产品推荐

