user9847788
user9847788

Reputation: 2445

How to upload a file in node.js server using multer

I'm trying to pass a file from my Angular app to a node.js server.

When I run the app, I get the following error: Error: Please choose files

HTML:

<upload name="fileUpload" formControlName="fileUpload" #fileUpload (listChange)="updateList($event)" data-kind="primary"
          [imagePreview]="true">
</upload>

Here is my updateList() method:

updateList(list: any) {
    this.demolist = Array.apply(this, list);
    this.attachmentReady.emit(this.demolist);
}

Node:

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const multer = require('multer');
let nodemailer = require('nodemailer');
let aws = require('aws-sdk');
const fs = require('fs');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
});

var upload = multer({ storage: storage });

app.post('/postData', upload.array('fileUpload', 12), (req, res, next) => {
    console.log(req.body);
    res.json(req.body);

    const files = req.files
    if (!files) {
        const error = new Error('Please choose files')
        error.httpStatusCode = 400
        return next(error)
    }
    res.send(files);
}

In a different project, multer is working as expected. Below is the HTML from that project:

<form action="/uploadmultiple" enctype="multipart/form-data" method="POST">
    Select images: <input type="file" name="myFiles" multiple>
    <input type="submit" value="Upload your files" />
</form>

The difference between my working code & the code that isn't working is that I'm able to use a standard input control if the type is file. But I need to use an upload control now & my code isn't working when I make that one change.

Can someone please tell me how I can use this control to pass the file? Thanks a lot in advance!

Upvotes: 0

Views: 359

Answers (1)

Gaurav Umrani
Gaurav Umrani

Reputation: 134

After you have installed multer using npm install --save multer

Basic usage example:

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/uploadmultiple', upload.single('myFiles'), function (req, res, next) {
  // req.file is the `myFiles ` file
  // req.body will hold the text fields, if there were any
})

app.post('/uploadmultiple', upload.array('myFiles', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

For more information you can read documentation here

Upvotes: 1

Related Questions