问题
I am trying to upload an image through the browser, but couldn't, I have got this working in Postman but couldn't figure out through browser. I am getting this error when trying with my code below :
Response {type: "basic", url: "http://localhost:3000/users/me/avatar", redirected: false, status: 400, ok: false, …}
My HTML code is :
<h1>Upload Profile Avatar</h1>
<form enctype="multipart/form-data" id="upload-avatar-form">
<input type="file" id="avatar-image" name="avatar">
<button id="avatar-upload-button">Upload</button>
</form>
My Server Side JS Code is :
const avatarUploadForm = document.querySelector( "#upload-avatar-form" );
avatarUploadForm.addEventListener( "submit", ( e ) => {
e.preventDefault();
console.log( 'function ran' );
const formData = new FormData();
const imgFile = document.querySelector( "#avatar-image" ).files;
formData.append( 'avatar', imgFile );
fetch( "http://localhost:3000/users/me/avatar", {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
"Authorization": `Bearer ` + `${ inMemoryToken }`
},
body: formData
} )
.then( res => {
console.log( res );
}
);
} );
My Node JS Backend Code is :
router.post(
"/users/me/avatar",
auth,
upload.single( "avatar" ),
async ( req, res ) => {
const buffer = await sharp( req.file.buffer )
.resize( { width: 200, height: 200 } )
.jpeg()
.toBuffer();
req.user.avatar = buffer;
await req.user.save();
res.status( 200 ).send();
},
( error, req, res, next ) => {
res.send( {
error: error.message,
} );
}
);
It would be great if you can keep the code in this or a similar style, cause on other functions, I have it similar, but any help is highly appreciated.
Please feel free to ask me if I can give any more clarity on question.
来源:https://stackoverflow.com/questions/63587902/how-to-upload-image-using-multer-through-browser