0

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.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • I don’t think you can just stringify a file like that (might work with simple text files). Just any file upload is a binary and you should use formData for this to post it, or use filereader to encode it. – MikeOne Dec 28 '20 at 20:00
  • Thanks. With formData I don't know how I can retrieve the data from the req. About file reader I use it in the frontend to read the file? – Hacen Selahy Dec 28 '20 at 20:32
  • For reading in node: https://stackoverflow.com/questions/4295782/how-to-process-post-data-in-node-js. Yes, you can use filereader to ‘stringify’ a (binary) file and send it as a value in a json post for example.. – MikeOne Dec 28 '20 at 20:42
  • Thank for your help. I think I need node and angular community so I can progress rapidly what you suggest to me because I get stuck for days on many problem – Hacen Selahy Dec 28 '20 at 20:51

1 Answers1

2

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

badrain
  • 301
  • 2
  • 5