2

For my angular + nodejs app, I have following to upload image:

file.ts

 handleFileInput(files: FileList) {
    var filename = files.item(0);
    this.upload(filename).subscribe();
};


upload(fileToUpload: File){   
  console.log(fileToUpload); //Here I can see all the image data     

  let obj = {
        imageData: fileToUpload,
        imageID: "Sample"
  };

  return this.http.post<any>(url, obj ,{});
}

Then in nodejs, uploadController.js

private initAPI(): void {
    this.router.route('/file')
        .post((req, res) => {
            console.log(req);   //No "body" data             
       });
}

When I get the data, I can see the following:

body:
   imageData: Object {}
   imageID: "Sample"

The imageData is empty. Any suggestions to how to send the image?

Thanks.

3
  • you have to send files as formData Commented Apr 24, 2018 at 5:20
  • 1
    on backend side are you using mutler for image uploading ? Commented Apr 24, 2018 at 5:21
  • Maybe this can help you stackoverflow.com/a/47938117/3085279 Commented Apr 24, 2018 at 5:30

2 Answers 2

5

This can be done using formData on angular side and to use multer on node side for uploading the file.

Angular Part

component.html

<div>
  <div>
    <input type="file" (change)="createFormData($event)">
  </div>
  <button (click)="upload()">Upload</button>
</div>

componenet.ts

  selectedFile: File = null;
  fd = new FormData();

  constructor(private http: HttpClient) {}

  createFormData(event) {
    this.selectedFile = <File>event.target.files[0];
    this.fd.append('file', this.selectedFile, this.selectedFile.name);
  }

  upload() {
    this.http.post(url, this.fd)
    .subscribe( result => {
      console.log(result)
    });
  }

Node Part

const express = require('express');
const router = express.Router();
var multer = require("multer");
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './upload')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})
const upload = multer({
    storage: storage
})

router.post('url',  upload.single('file'), (req, res) => {
  // the file is uploaded when this route is called with formdata.
  // now you can store the file name in the db if you want for further reference.
  const filename = req.file.filename;
  const path = req.file. path;
  // Call your database method here with filename and path
  res.json({'message': 'File uploaded'});
});

module.exports = router;
Sign up to request clarification or add additional context in comments.

Comments

0
install ng2-file-upload
npm i ng2-file-upload --save

component.html

<label class="image-upload-container btn btn-bwm">
  <span>Select New Image</span>
  <div *ngIf="selectedFile">
    <img src="{{selectedFile.src}}" class="img_profile img-circle" >
   </div>
  <input #imageInput
         type="file"
         accept="image/*" ng2FileSelect [uploader]="uploader"
         (change)="processFile(imageInput)" name="newImage">
</label>

app.module.ts

import { FileSelectDirective } from 'ng2-file-upload';

//in declaration
declarations: [ ...,
FileSelectDirective,
... ],

component.ts

 import { Component, OnInit,ViewContainerRef,ElementRef,ViewChild } from '@angular/core';
import {  FileUploader } from 'ng2-file-upload/ng2-file-upload';
//Set api url
const URL = 'http://127.0.0.1:3000/users/uploadFile';


//Apply for preview. add before export class
class ImageSnippet {
pending: boolean = false;
  status: string = 'init';
 constructor(public src: string, public file: File) {}
}


 @Component({
  selector: 'app-imageupload',
  templateUrl: './imageupload.component.html',
  styleUrls: ['./imageupload.component.css']
})
//export class
export class ImageuploadComponent implements OnInit {
  public name:any
  constructor() { }

    selectedFile: ImageSnippet;
   
  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);
     };
  }
  processFile(imageInput: any) {
    const file: File = imageInput.files[0];
    const reader = new FileReader();

    reader.addEventListener('load', (event: any) => {

      this.selectedFile = new ImageSnippet(event.target.result, file);
      console.log(this.selectedFile.file);
    })
    reader.readAsDataURL(file);
                
   this.uploader.uploadAll();
  
}
 public uploader:FileUploader = new FileUploader({url: URL, itemAlias: 'newImage'});
  
 
}

Node Part

var express = require('express');
var app = express();
var multer = require('multer');
var path = require('path');


//Apply Path to diskStorage and File Name with extension
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, '../src/assets/uploads/')
    },
    filename : function(req, file, callback) {
        console.log(file)
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
  });
   //Store in storage
    const upload = multer({
        storage: storage
    });
//For Single File upload
const singleUpload = upload.single('newImage');

var imageName='';
//upload file api to upload file
app.post('/uploadFile',function(req,res){
    
    singleUpload(req, res, function(err) {
       
        if (err) {
            return res.status(422).send({errors: [{title: 'File Upload Error', detail: err.message}] });
        }else{
            imageName =  req.file.filename;
            console.log(req.file.path);
            var imagePath = req.file.path;
            return res.send({success:true,  imageName});
        }
    })
});

 module.exports = app

Comments

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.