0

I'm trying to do single file upload using multer. Although I'm able to upload a file manually in the relevant folder using tools like postman for testing the express route, I cannot upload it using Angular frontend. I created a folder called uploads in the node backend folder where the files are supposed to get uploaded. Also I need to upload the file within a form and pass it to a api where it should take the file along with other parameters also. But unfortunately, it is returning status 500 with Internal Server Error on the browser console while on my node terminal it is returning Cannot read property 'path' of undefined.

My node backend code which is working fine is below:

const multer = require('multer')

const storage = multer.diskStorage({

destination: function(req, file, cb) {

cb(null, './uploads/')

},

filename: function(req, file, cb) {

cb(null, Date.now() + file.originalname)

}

})

const upload = multer({storage: storage})

let baseUrl = appConfig.apiVersion+'/blogs';

app.post(baseUrl+'/create', upload.single('imagePath'), (req, res) => {
    var today = time.now()
    let blogId = shortid.generate()

    let newBlog = new BlogModel({

        blogId: blogId,
        title: req.body.title,
        description: req.body.description,
        bodyHtml: req.body.blogBody,
        isPublished: true,
        category: req.body.category,
        author: req.body.fullName,
        created: today,
        lastModified: today,
        imagePath: req.file.path    //node console is pointing towards this point
    }) // end new blog model

    let tags = (req.body.tags != undefined && req.body.tags != null && req.body.tags != '') ? req.body.tags.split(',') : []
    newBlog.tags = tags

    newBlog.save((err, result) => {
        if (err) {
            console.log(err)
            res.send(err)
        } else {
            res.send(result)

        }
    }) // end new blog save
});

Below is my Angular Component code which is not working:

selectImage(event) {
    if(event.target.files.length > 0){
      const file = event.target.files[0];
      this.images = file;
    }
  }

  public createBlog(): any {

    const formData = new FormData();
    const form = formData.append('imagePath', this.images);


    let blogData = {
      title: this.blogTitle,
      description: this.blogDescription,
      blogBody: this.blogBodyHtml,
      category: this.blogCategory,
      imagePath: form 
    } //end blogData

    console.log(blogData);

    this.blogHttpService.createBlog(blogData).subscribe(

      data => {
        console.log(data);
        this.toastr.successToastr('Blog Posted Susseccfully!', 'Success!');
        setTimeout(() =>{
          this.router.navigate(['blog', data.blogId]);
        }, 1000)

      },

      error => {
        console.log(error);
        console.log(error.errorMessage);
        this.toastr.errorToastr('This is not good!', 'Oops!');
      })
  }

Angular Service code

public createBlog(blogData): any {
    let myResponse = this._http.post(this.baseUrl + '/create', blogData);
    return myResponse;

  }

Frontend HTML Code:

<div>

<input type="file" name="imagePath" (change)="selectImage($event)" />

</div>

1 Answer 1

1

It seems like you created a formData object, but you are not actually doing anything with it. As you can see here, you are building up an object and sending it along with your request, but it does not include your formData

let blogData = {
      title: this.blogTitle,
      description: this.blogDescription,
      blogBody: this.blogBodyHtml,
      category: this.blogCategory,
      imagePath: this.imagePath
    } //end blogData

    console.log(blogData);

    this.blogHttpService.createBlog(blogData).subscribe(

Not entirely sure what the exact syntax would be in your case, but here you can see some sample code I have in a project of mine which will hopefully give you an idea.

changeHandler(e) {
    const fd = new FormData();
    fd.append('sample', e.target.files[0]);
    axios.post('/save-image', fd).then(i => {
      this.setState({img: i.data.filename});
    });
  }

As you can see, the formData is what I am actually sending to the server.

Sign up to request clarification or add additional context in comments.

1 Comment

did this out but no help. Still getting Cannot read property 'path' of undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.