1

i am new in nodejs development and express I learn MEAN stack nad now i don`t know how i can do this staff in n In my route i have this code

var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({ dest: __dirname + '/public/uploads/' });

router.post('/', upload.single('file'), function(req, res) {
   console.log(req.file);
   res.status(200).json({ file: req.file});
});
module.exports = router;

But i saving not image. How i can save an image file? I mean some decode function or what?

In console i see this :

{ fieldname: 'file',
 originalname: 'my.jpg',
 encoding: '7bit',
 mimetype: 'image/jpeg',
 destination: '/home/path/mean/public/uploads/',
 filename: '8b6256d4af77641c844480f05806e959',
 path: '/home/path/mean/public/uploads/8b6256d4af77641c844480f05806e959',
 size: 19486 
 }

Thanks.

2
  • If you are getting a filename, path, and size, the file is being saved. Is the file not in path specified? Commented Nov 12, 2015 at 21:04
  • the file here, but not *.jpg/.png Commented Nov 13, 2015 at 8:19

2 Answers 2

1

So this code works for me. Right now i need to think how i would be save the image in collection of new post. Smth like - i click the save image and save image on folder and after response i my ng-model will be post.image = response.image, after i save all body of post in collection.... I don`t know, in PHP it will be in one reuqest :) I am very new with nodejs, it is just for fun, not for work. I like JavaScript. :)

var multer  = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });

var fs = require('fs');


fs.writeFile('public/uploads/image.jpg', req.file.buffer, 'ascii', 
 function  (err) {
  if (err) throw err;
    console.log('It\'s saved!');
 }
);
Sign up to request clarification or add additional context in comments.

Comments

0
var multer = require('multer'); 

var storage = multer.diskStorage({  
    destination: function (req, file, cb) { 
        cb(null, 'public/upload')
    },
    filename: function (req, file, cb) {
        cb(null, uuid.v4() + path.extname(file.originalname));
    }
})

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

This code helped me to achieve the goal. it will store the image with random name and the extension.

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.