node.jsangularangular-fullstack

Send a file from Angular to Node.js


I am creating a form to allow users to upload their files. I am using Angular for the front end and Node.js/MySQL for the backend. However, I am getting an error. When I try to send file from Angular to Node.js, the file doesn't get received. I read somewhere on stack overflow that one can send a file in the http headers. Can anybody tell me what am I doing wrong? Here's my code:

xxxx.component.html (Angular)

<div class="input-group">
    <div class="input-group-prepend">
 </div>
 <div class="custom-file">
   <input type="file" class="custom-file-input" [(ngModel)] = "fU" name = 
    "FileUpload" id="inputGroupFile01"
     aria-describedby="inputGroupFileAddon01" required>
     <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
 </div>
</div>

xxxx.component.ts (Angular)

private onCreatePosts(form: NgForm)
{
    this.http.post('http://localhost:3000/post', form.value)
    .subscribe(responseData => {
      console.log(responseData);
    }
    ,error => {
      this.connectionToServerFailed = true;
    });
 }

Node.js

router.post("/post", (req, res) =>{
var fileupload = req.body.FileUpload;
console.log(fileupload);
console.log(fileupload.name);
})

Here's the output that I am getting when I try to upload a file:

C:\fakepath\testfile.docx
undefined

I have tried different things, but still unable to progress any further. Can anybody tell me why I am getting this error of undefined and fakepath.

EDIT: When I try to access the file, it only prints the path not the file. The angular Http request is only sending the path of the file not the file itself. EDIT: Editing this question again so, that somebody can help. EDIT: I have tried working with a lot of different things but nothing is working for me. The node.js is only getting the path of the file, not the file itself.


Solution

  • Files will not be part of the request out of the box; they have to be stored temporarily on disk or in memory in Node.js. Try something like multer: https://medium.com/javascript-in-plain-english/uploading-files-using-multer-on-server-in-nodejs-and-expressjs-5f4e621ccc67