我正在使用multer上传文件,它似乎在api端工作,但这是在前端的问题:
fetch(`${path}`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: file,
}).then((response) => {
return response.status;
});如果我添加'multipart/form-data',则会出现以下错误:"Multipart: Boundary not found“
否则,"file“在控制器中未定义
下面是控制器:
@ApiConsumes('multipart/form-data')
@ApiFile('file')
@UseInterceptors(
FileInterceptor('file', multerOptions([MimeExtEnum.XLS, MimeExtEnum.XLSX])),
)
@Post('/uploadFile')
public async uploadFile(
@UploadedFile() file,
): Promise<any> {
console.log("file", file); //here the file is undefined
}发布于 2021-06-04 22:35:00
当你在前端发送一个带有fetch的表单时,不要自己设置Content-Type头。如果这样做,它将不会有表单边界,并且multipart/ form -data请求将在后端被错误地解析。
您可以省略标头,因为浏览器会为您设置标头,其中包含一个唯一的边界。
头你的头:Content-Type=multipart/form-data;
Content-Type=multipart/form-data; boundary=------WebKitFormBoundaryg7okV37G7Gfll2hf-- 其次,要发送文件,首先需要使用FormData API构造表单,将文件附加到表单,然后将表单发送到后端。
下面是它的外观:
// Construct a form and append the file to it
const form = new FormData();
form.append('file', file);
// Send multipart/form-data request with fetch
// Note: don't set `Content-Type` header manually, the browser does this for you
fetch(`${path}`, {
method: 'POST',
body: form,
}).then((response) => {
return response.status;
});https://stackoverflow.com/questions/67837186
复制相似问题