Jest+Supertest中PUT请求.attach上传文件无效的解决咨询
问题解决:Supertest PUT 请求二进制文件上传
你的核心问题是用错了请求构造方式:.attach() 是用于构造 multipart/form-data 类型的表单上传请求,但你在 Postman 中用的是二进制上传(请求体直接是文件的二进制内容),两者的请求格式完全不同,导致接口虽然返回200但实际没正确接收文件。
正确的实现方式
不需要用 .attach(),而是直接读取文件的二进制内容作为请求体发送,同时保留正确的 Content-Type 头:
import * as fs from 'fs'; import request from 'supertest'; export async function uploadFileForJob( uploadUrl: string, accessToken: string, filePath: string ) { // 读取文件的二进制内容 const fileBuffer = fs.readFileSync(filePath); const upload_file_for_job = await request(uploadUrl) .put("") .set("Authorization", `Bearer ${accessToken}`) .set("Content-Type", "model/gltf-binary") .send(fileBuffer); // 直接发送文件buffer作为请求体 return upload_file_for_job; }
为什么原来的写法不行?
.attach('file', filePath) 会自动把请求的 Content-Type 改成 multipart/form-data; boundary=xxx,同时构造包含文件字段的表单结构,这和你在 Postman 中选择的「二进制」上传模式完全不匹配——接口期望的是纯二进制的请求体,而不是表单格式的数据,所以即使返回200,也没有正确处理文件内容。
验证修改
保持测试文件的调用代码不变,重新运行测试:
const UploadFileForJob = await uploadFileForJob( uploadUrl, accessToken, 'C:/Job/Simulations/TestTshirt_04.glb' ); expect(UploadFileForJob.status).toEqual(200); // 再调用检查接口 const GetJobView = await getJobView(jobId, accessToken); expect(GetJobView.status).toEqual(200); expect(GetJobView.body.view).toBeTruthy();
这样就能和 Postman 的二进制上传行为一致,接口应该能正确接收文件了。
内容的提问来源于stack exchange,提问作者xyarriddi
相关产品推荐
相关产品推荐

