Reputation: 504
I'm creating a Nest.js server application, and I have already added the upload file functionality, as follows:
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
upload(@UploadedFile() file: Express.Multer.File) {
console.log(file);
}
If I try this endpoint on postman or insomnia all works just fine, the problem begins when I try it using JavaScript/React, so, I have the following code in my React.js project:
function App() {
const [state, setState] = useState(null);
const handleChange = e => {
console.log(e.target.files);
setState(e.target.files[0]);
};
const handleSubmit = async e => {
e.preventDefault();
const url = 'http://localhost:3000/upload';
const formData = new FormData();
formData.append('file', state);
console.log(JSON.stringify(formData));
const response = await fetch(url, {
method: 'POST',
body: formData,
headers: {
'content-type': 'multipart/form-data; boundary=X-INSOMNIA-BOUNDARY',
Accept: '*/*'
}
});
console.log(response);
};
return (
<div>
<input type="file" name="files" onChange={handleChange} />
<button onClick={handleSubmit}>Upload</button>
</div>
);
}
If I send the request here I get a 500
response from the server and the terminal of the server throws me the following error:
[Nest] 111577 - 12/10/2022, 19:18:39 ERROR [ExceptionsHandler] Unexpected end of form Error: Unexpected end of form
Does anyone know why this error is? and why don't I get this error in postman?
Upvotes: 0
Views: 1489
Reputation: 1507
I solved the same problem (actually with Express and Multer instead of NestJS and Multer) by downgrading Multer to 1.4.3.
See https://github.com/expressjs/multer/issues/1144
Upvotes: 1