FormData 传 XML 文件需用 Blob 或 File 对象,显式指定文件名,fetch 不设 Content-Type;后端须从文件对象而非 body 读取,注意网关上传限制。
XML 文件本质是文本,但浏览器上传时必须作为 Blob 或 File 对象传入,不能直接传字符串。否则后端收到的是纯文本内容,丢失文件名、MIME 类型,且部分服务端框架(如 Express 的 multer)会跳过解析。
常见错误:
formData.append('file', '- 1
');——这传的是字符串,不是文件。
new Blob([xmlString], { type: 'application/xml' }) 包装 选中 XML 文件,直接取 input.files[0],它已是 File 对象(继承自 Blob)Blob 时,type 设为 'application/xml' 或 'text/xml',避免被识别为 text/plain
FormData.append() 的第三个参数是文件名。不传会导致后端无法获取原始文件名(例如 PHP 的 $_FILES['file']['name'] 为空,Node.js 的 multer 默认 fallback 为 undefined)。
File 对象(来自 input),文件名已内置,可省略:formData.append('file', fileInput.files[0]);Blob 构造,则必须补上文件名:const blob = new Blob([''], { type: 'application/xml' });
formData.append('file', blob, 'config.xml');formData.append('file', blob) —— 后端看到的文件名可能是 blob 或空字符串使用 fetch 上传 FormData 时,**绝对不要手动设置 Content-Type 头**。浏览器会自动设置为 multipart/form-data; boundary=...,并注入正确的分隔符和字段

fetch('/upload', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' }, // ← 删掉这行
body: formData
});fetch('/upload', {
method: 'POST',
body: formData // 让浏览器自己设 header
});Content-Type 会导致 boundary 缺失,后端解析失败,常见报错如 Multipart: Boundary not found(Express + multer)或 400 Bad Request
前端发得对,不代表后端能正常读。关键点在于:XML 是文件上传,不是 JSON 提交,所以不能依赖 req.body(那是表单 URL-encoded 或 JSON 解析后的结果)。
'file')与 upload.single('file') 中一致,文件在 req.file 而非 req.body
request.files.get('file'),不是 request.form
$_FILES['file']['tmp_name'],不是 $_POST
413 Payload Too Large,需检查 client_max_body_size