0

I'm working on an angular 9 app and I want to build a file upload system which will be able to send files from the client side to our server and store them in the assets folder.

The issue is I don't know how to send the file to the server and store it in the assets folder.

In backend I'm working with nodejs.

Your help right here will be highly appreciated.

zakaria mouqcit
  • 393
  • 2
  • 4
  • 17

1 Answers1

2

There are two ways; - store your image in base64 in your DB (check about this post : BASE64 to image angular 2)

  • Front-side, get the file with file upload, appends it to a FormData object. If it's a simple upload, you can append this way :
FormData.append('upload', upload, extraParam to define the file name);

If it's a multiple upload, this way :

for (let i = 0; i < files.length; i++) {
      FormData.append('uploads[]', files[i], extraParam to define the file name);
    }

Then, in the back-side, it's preferable to use multer (https://github.com/expressjs/multer)

There is a sample for multiple uploads :

const multer = require('multer');

const MIME_TYPE_MAP = {
  'image/png': 'png',
  'image/jpeg': 'jpeg',
  'image/jpg': 'jpg'
};

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const isValid = MIME_TYPE_MAP[file.mimetype];
    let error = new Error('Invalid mime type');
    if(isValid) {
      error = null;
    }
    cb(error, "backend/images/photos");
  },
  filename: (req, file, cb) => {
    const name = file.originalname.toLowerCase().split(' ').join('-');
    const ext = MIME_TYPE_MAP[file.mimetype];
    cb(null, name + '-' + Date.now() + '.' + ext);
  }
});

module.exports = multer({storage: storage}).array("uploads[]", numberOfMaxUploads);

And there is for a simple upload :

const multer = require('multer');

const MIME_TYPE_MAP = {
  'image/png': 'png',
  'image/jpeg': 'jpeg',
  'image/jpg': 'jpg'
};

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const isValid = MIME_TYPE_MAP[file.mimetype];
    let error = new Error('Invalid mime type');
    if(isValid) {
      error = null;
    }
    cb(error, "backend/images/photos");
  },
  filename: (req, file, cb) => {
    const name = file.originalname.toLowerCase().split(' ').join('-');
    const ext = MIME_TYPE_MAP[file.mimetype];
    cb(null, name + '-' + Date.now() + '.' + ext);
  }
});

module.exports = multer({storage: storage}).single("image");

There, my multer package is called as a middleware on my route on the back-end. You can do it this way :

const extractFile(s) = require('../middlewares/files/extractFile');
router.post("", extractFile(s), nextCall(Middleware or controller.method);
Bobby
  • 101
  • 7