使用FormData提交POST请求如何设置content-type且不附带filename参数
解决方案
有两种可落地的方案可以同时满足指定字段Content-Type、不携带filename参数的需求:
方案1:使用FormData.append的第三个参数(优先推荐,适配绝大多数现代浏览器)
FormData.append方法支持第三个可选参数,用于指定Blob类型值的文件名,浏览器默认填充值为"blob"。你只需要在调用append时主动传入空字符串作为第三个参数,即可去除filename字段,同时保留Blob本身设置的Content-Type属性。
修改后的实现代码如下:
const formData = new FormData(); const obj1 = new Blob([json_data], {type: 'text/plain; encoding=utf-8'}); formData.append("small_config", obj1, ""); // 第三个参数传入空字符串 const obj2 = new Blob([client], {type: 'text/plain; encoding=utf-8'}); formData.append("app_type", obj2, ""); const obj3 = new Blob([version], {type: 'text/plain; encoding=utf-8'}); formData.append("product_version", obj3, ""); let thumb = await fetch(my_url, { method: 'POST', mode: 'cors', cache: 'no-cache', credentials: 'same-origin', redirect: 'follow', referrerPolicy: 'no-referrer', body: formData });
修改后对应表单条目的请求头会变为如下格式,无filename参数:
Content-Disposition: form-data; name="small_config"
Content-Type: text/plain; encoding=utf-8
方案2:手动构造multipart/form-data请求体(兜底兼容方案,完全可控)
如果需要兼容老旧浏览器,或是对请求头有更高的自定义要求,可以手动拼接multipart格式的请求体,完全自主定义每个字段的头信息,从根源上避免filename参数生成。
实现代码如下:
// 生成随机边界字符串,避免和请求内容冲突 const boundary = '----CustomFormBoundary' + Math.random().toString(16).slice(2); const body = []; // 封装添加表单字段的方法 const addFormField = (name, value, contentType) => { body.push(`--${boundary}`); body.push(`Content-Disposition: form-data; name="${name}"`); body.push(`Content-Type: ${contentType}`); body.push(''); body.push(value); }; // 按需求添加所有字段 addFormField('small_config', json_data, 'text/plain; encoding=utf-8'); addFormField('app_type', client, 'text/plain; encoding=utf-8'); addFormField('product_version', version, 'text/plain; encoding=utf-8'); // 添加结束边界标记 body.push(`--${boundary}--`); let thumb = await fetch(my_url, { method: 'POST', mode: 'cors', cache: 'no-cache', credentials: 'same-origin', redirect: 'follow', referrerPolicy: 'no-referrer', headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` }, // 按multipart规范用\r\n拼接所有内容 body: body.join('\r\n') });
内容的提问来源于stack exchange,提问作者Bartosz Włodarczyk
相关产品推荐
相关产品推荐

