-1


I have a form with text-fields & drop-downs.
I am using Node.js , Angular js, Express, MongoDb.
I want to post data along with image(s).
I want to store image in folder, without any base/binary conversion, and image path should be stored in mongoDb.
How can I achieve this?

mayank bisht
  • 618
  • 3
  • 14
  • 43

3 Answers3

1

HTML FILE

<div class="form-group">
  <label class="col-md-4">Profile Photo</label>
  <input type="file" class="form-control" 
  formControlName="s_profile" 
  #s_profile ng2FileSelect 
  [uploader]="uploader" 
  (change)="uploader.uploadAll()" />
</div>
<div class="form-group">
  <button (click)="addfile()" 
  [disabled]="angForm.pristine || angForm.invalid"
  class="btn btn-primary">Upload</button>
</div>

COMPONENT FILE

const URL = 'http://localhost:4000/api/upload';
public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo'});
ngOnInit() {
  this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
  this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
    //console.log('ImageUpload:uploaded:', item, status, response);
    console.log(response);
    this.profilPhotos = response;
  };
}
addfile(){
  this.ss.addStudent(this.profilPhotos);
}

SERVICE FILE

uri = 'http://localhost:4000/business';
addBusiness(uploadImages) {
  const obj = {uploadImages: uploadImages};
  this.http.post(`${this.uri}/add`, obj)
    .subscribe(res => console.log('Done'));
}

SERVER FILE

const DIR = '../src/assets/upload';
let storage = multer.diskStorage({
destination: (req, file, cb) => {
  cb(null, DIR);
},
filename: (req, file, cb) => {
  console.log(file);
  cb(null, file.originalname);
}
});
let upload = multer({storage: storage});
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.post('/api/upload',upload.single('angular'), function (req, res) {
if (!req.file) {
  console.log("No file received");
  return res.send({
    success: false
  });
} else {
  console.log('file received');
  return res.send(req.file.filename)
}
});

ROUTER FILE

const path = require('path');
const fs = require('fs');
const express = require('express');
const multer = require('multer');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
const DIR = './uploads';
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + '.' + path.extname(file.originalname));
}
});
let upload = multer({storage: storage});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.post('/api/upload',upload.single('photo'), function (req, res) {
if (!req.file) {
return res.send({
success: false
});
} else {
return res.send({
return res.send(req.file.filename)
})
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, function () {
console.log('Node.js server is running on port ' + PORT);
});
Community
  • 1
  • 1
Harsh Patel
  • 21
  • 1
  • 5
0

Front-End:

HTML:

<input type="file" nv-file-select uploader="vm.uploader"
       id="fileUpload" ng-model="vm.schema.file"/>Browse

Controller:

  angular
  .module('myApp')
  .controller('myController', myController);

  myController.$inject = ['FileUploader'];

  function EditSchemaBasicController(FileUploader) {
    vm.uploader = new FileUploader({
          url: "https://localhost:3000/api/file", //your api URL
          queueLimit: 10, 
          onAfterAddingFile: function(item) {
            //before upload logic will go here like file size and extension handling
            item.upload();
          },
          onCompleteItem: function(item, response){
            //on complete
            console.log('Uploaded File: ' + response.file);
          },
          onErrorItem: function(item, response) {
            //error handling
          }
        });
    }

Back-End:

'use strict'
var express = require('express');
var router = express.Router();
var fs = require('fs-extra');

//Post file.. i used busboy to upload the file
router.post('/', function(req, res, next) {
  req.pipe(req.busboy);
  req.busboy.on('file', function (fieldname, file, filename) {    
    filename = decodeURI(filename);
    //Path where file will be uploaded
    var fstream = fs.createWriteStream('API/Images' + filename);
    file.pipe(fstream);
    fstream.on('close', function () {
      res.status(201).json({file: filename});
    });
  });
});

module.exports = router;
Surjeet Bhadauriya
  • 6,755
  • 3
  • 34
  • 52
0

You can use the simple/lightweight ng-file-upload directive. It supports drag&drop.

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
  $scope.onFileSelect = function($files) {
  Upload.upload({
    url: 'api/upload',
    method: 'POST',
    file: $files,            
  }).progress(function(e) {
  }).then(function(data, status, headers, config) {
    // file is uploaded successfully
    console.log(data);
  }); 

}];

You can use formidable for parsing form data, especially file uploads. Read more here

app.post('/api/upload', function(req, res) {
    var form = new formidable.IncomingForm();


    form.multiples = true;

    form.uploadDir = path.join(__dirname, '../../public/images');


    form.on('file', function(field, file) {

        //copy file to new path
        fs.renameSync(file.path, path.join(form.uploadDir, file.name));

        var Image = path.join(form.uploadDir, file.name);
        //save new path to mongodb

        db.collection('images').insert({
            imagePath: Image
        }, function(err, result) {
            // do your stuff
        })


    });
})

This is just my suggestion. You should learn more and do what you expect. Hope it help.

Burdy
  • 603
  • 4
  • 11