How to upload image using multer through browser?

十年热恋 提交于 2021-02-17 06:09:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!