test team
test team

Reputation: 767

How to upload images using NodeJs?

I want to upload the product images using Node Js. So I used multer to upload images. I used postman to test whether it is work, but it returns Please upload a file. I changed another image then it says PayloadTooLargeError: request entity too large.

Unable to detect image

ayloadTooLarge

MyCode

const express = require("express");
const router = express.Router();

const multer = require('multer');
const storage = multer.diskStorage(
{
    destination: function(req, file, cb)
    {
        cb(null, './uploads/');
    },
    filename: function(req, file, cb)
    {
        cb(null, new Date().toISOString() + file.originalname);
    }
});

const fileFilter = (req, file, cb) =>
{
    // reject a file
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png')
    {
        cb(null, true);
    }
    else
    {
        cb(null, false);
    }
};

const upload = multer(
{
    storage: storage,
    limits:
    {
        fileSize: 1024 * 1024 * 50
    },
    fileFilter: fileFilter
});


router.post("/upload", upload.single('productImage'), (req, res, next) =>
{
    if (!req.file)
      return res.send('Please upload a file')
    var tempPath = req.file.path
      console.log(tempPath);
});

package.json

{
  "name": "api",
  "version": "1.0.0",
  "description": "testing version",
  "main": "server.js",
  "dependencies": {
    "express": "^4.16.4",
    "multer": "^1.3.0",
    "nodemon": "^1.18.10",
  },
  "devDependencies": {},
  "scripts": {
    "test": "node server.js",
    "start": "nodemon server.js"
  },
  "keywords": [
    "api"
  ],
  "author": "tteam",
  "license": "ISC"
}

Upvotes: 0

Views: 3418

Answers (3)

Aryan
Aryan

Reputation: 3626

It will become easy to store files after converting in string you just have to convert string in image in your frontend

Convert image in to base64 string using this code in your api and also don't forgot to delete file from upload folder

"img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")

To delete the file

let resultHandler = function (err) {
    if (err) {
        console.log("unlink failed", err);
    } else {
        console.log("file deleted");
    }
}
fs.unlink(req.file.path, resultHandler);

At your routes import multer:

const multer = require('multer');
const upload = multer({ dest: __dirname + '/uploads/images' });`

Add upload.single('img') in your request:

router.post(
    '/fellows-details',
    authorize([Role.ADMIN, Role.USER]), 
    upload.single('img'),
    usersController.fellowsdetails
);

If you don't use the unlink function it cause error because it first store buffer values in folder and than convert it to base64.

Upvotes: 1

Sridhar
Sridhar

Reputation: 11786

Error: ENOENT: no such file or directory, open 'C:\Users\ttest\Downloads\Compressed\uploads-master\api\routes\uploads\2019-04-18T14:02:45.456Z55460132_25_63992_n (1).jpg'

I think the issue seem to be with location where you store the uploaded file. You need to check for existence of upload/ before storing the file.

user.js

const path = require('path');
const fs = require('fs-extra');

let UPLOAD_LOCATION = path.join(__dirname, 'uploads');
fs.mkdirsSync(UPLOAD_LOCATION); //create `uploads/` folder, if it doesn't exists

Use this location for storing the upload file

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, UPLOAD_LOCATION);
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  }
});

For reference, you can check how to configure upload path in multer

Upvotes: 0

Faiz Khan
Faiz Khan

Reputation: 298

Your code is working fine i just have to change the upload.single('productImage') to upload.single('image') and i did not face any error like Please upload a file, Here is my pen it just same as yours and works fine.

https://codepen.io/khanChacha/pen/rbJjYj

Please upload a file only occur if you don't choose any file or choose wrong file type

I have updated your code and made few changes now its working check it here:

https://github.com/faiz1996khan/uploads

Upvotes: 1

Related Questions