Upload image in Angular 4 and save to Mongoose DB

There are other questions out there about uploading images with Angular 4, but NO comprehensive answers. I have played around with ng2-file-upload and angular2-image-upload, but can't get them to save in my Mongo/Mongoose DB. Here is what I have to far...

Component HTML:

<form (submit)="newProduct(formData)" #formData="ngForm">
  <div class="form-group">
    <label for="name">Product Name:</label><input type='text' name='name' class="form-control" id="name" ngModel>
  </div>
  <div class="form-group">
    <label for="image">Image:</label><input type="file" name='image' class="form-control" id="image" ngModel>
  </div>
  <div class="form-group">
    <label for="description">Description:</label><input type='text' name='description' class="form-control" id="description" ngModel>
  </div>
  <div class="form-group">
    <label for="quantity">Quantity:</label><input type='number' name='quantity' class="form-control" id="quantity" ngModel>
  </div>
  <button type="submit" class="btn btn-default">Add</button>
</form>

Component.ts

import { Component, OnInit } from '@angular/core';
import { AddService } from './add.service';
...
export class AddComponent implements OnInit {

  constructor(private _addService:AddService) { }

  ngOnInit() {
  }

  newProduct(formData){
    this._addService.addProduct(formData.value)
        .then(()=>{
          formData.reset()
        })
        .catch(err=>console.log(err))
  }
}

Compoenent service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs';

@Injectable()
export class AddService {

  constructor(private _http:Http) { }

  addProduct(newprod){
    return this._http.post('/api/newprod', newprod).map((prod:Response)=>prod.json()).toPromise();
  }
}

Controller

  addProduct:(req,res)=>{
    let newProd = new Product(req.body);
    newProd.save((err,savedProd)=>{
      if(err){
        console.log("Error saving product");
      } else {
        res.json(savedProd);
      }
    })
  },

Schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
  name: {type:String,required:true},
  image: {data:Buffer, contentType:String},
  description: {type:String,required:true},
  quantity: {type:Number,required:true},
}, {timestamps:true})
var Product  = mongoose.model('Product', ProductSchema);

All of the other inputs make it back to the DB fine. What do I need to do to get the images saving properly?

1 answer

  • answered 2017-06-17 18:17 Jonnysai

    I am afraid you can't directly upload image like that. First you can access image data from file tag and assign into formdata.

    you can try like this.In your component

        newProduct(formData){
        let inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#image');   
               let fileCount: number = inputEl.files.length;   
                let formData = new FormData();  
                if (fileCount > 0) {
                        formData.append('image', inputEl.files.item(0));
                 }
    
    this._addService.addProduct(formData.value)
            .then(()=>{
              formData.reset()
            })
            .catch(err=>console.log(err))
      }
    
        }
    

    this is not exact working solution but you can start like this.