Hacen Selahy
Hacen Selahy

Reputation: 79

How I can save file in nodejs?

I use angular in frontend and has this code: In app.component.html

<input type="file" (onchange)="handlefile($event)">

In app.component.ts

file: File | null = null

handlefile(event:any): void{
    this.file = event.target.files.item(0);
}

uploadfile(){
    this.uploadservice.postFile(this.file);
}

In uploadservice.service.ts:

postFile(file: File|null): void{
    if(file!=null){
        let headers = new HttpHeaders({
          'Content-Type':'application/json'
        });
        var json = JSON.stringfy({file: file});
        this.http.post('http://localhost:3000/mpost',json, {headers: headers});
    }
}

At the backend :

app('/mpost', (req, res) => {
    console.log(req.body.file)
});

In nodejs console I got this {}. I am asking how I can save this file or add it to a mongoose schema.

Upvotes: 0

Views: 356

Answers (1)

Iron
Iron

Reputation: 311

Try using an Express middleware, such as express-fileupload npm express-fileupload. Here is the full tutorial: How to upload files in Node.js and Express

Upvotes: 2

Related Questions