0

I am trying to upload files to the server. I created an Express-App with an index.html and an index.js file.

The index.html file:

<h1>File Upload in Node.js App</h1>
<form method="POST" action="/" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>

The index.js file:

app.post('/', (req,res)=>{
    console.log("post file")
    if(req.files){
        console.log(req.files);
        var file = req.files.file
        var filename = file.name;
        console.log(filename);

        file.mv('./uploads/' + filename, function(err){
            if(err){
                res.send(err)
            } else {
                res.send("File Uploaded")
            }
        })
    }
})

It worked very well. I am trying the post method now within my Angular-App

app.component.html

<h1>File Upload in Node.js App</h1>
<input type="file" (change)="fileChange($event)" name="file">
<button (click)="uploadFiles()">Upload</button>

app.component.ts:

    fileChange(element) {
      this.files_to_upload = element.target.files;
      console.log(this.files_to_upload);
    }

    uploadFiles(){
        const body = {
            files: this.files_to_upload
        }
        console.log(body);
       this.http.post("http://localhost:3000/",body)
        .subscribe(res => console.log(res));
        

The body is different when using the form but why? In my Express-App req.files is not initialized because the function is just console logging Post file and stops there.

What is the difference between the two approaches (their bodies) and why does my approach in my Angular-App not work? What would I have to change? I do not get it.

G.Don
  • 17
  • 6
  • i think you should use FormData when sending the file via post in angular, see this answer for example: https://stackoverflow.com/questions/47936183/angular-file-upload – Frank Adrian Jun 22 '20 at 13:37
  • Thank your for sharing the link! I will try it ! – G.Don Jun 22 '20 at 13:38

0 Answers0