probably a stupid question but maybe someone here could help me.
after uploading files with multer and express, what would be the url of the uploaded files to uploads/?
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
}
});
if it's an image, how can i link to it like:
http://localhost:3000/uploads/image.jpg?
should i place the uploaded files in the public directory?
thanks
This is how I setup Multer for expressjs. First you have to overwrite the renaming function if you want to keep the original filename. Then you have to move the uploads folder to the public folder.
// this uploads a single input[file] field called 'image'
var express = require('express'),
multer = require('multer'),
upload = multer({
storage: multer.diskStorage({
destination: 'public/images/uploads/',
filename: function(req, file, cb) {
// this overwrites the default multer renaming callback
// and simply saves the file as it is
cb(null, file.originalname)
}
})
}),
router = express.Router()
// add route
router.post('/uploadimage', upload.single('image'), function(req, res, next) {
if (!req.file) return next(new Error('Select a file!'))
// be careful here as the upload path has 'public' at the start
// which is the static mounted directory so doesn't show
// here the path is build manually
var imagePath = '/images/uploads/' + req.file.filename;
res.end('<img src=" + imagePath + " />')
})
additionally you can keep the default upload path as /uploads and mount it as a static folder
// Mount uploads
app.use(express.static(path.resolve('./uploads')));
Make static teh diskstoarge location in your case 'uploads' folder should be static
app.use(express.static('uploads'));
https://expressjs.com/en/starter/static-files.html
Related
I'm a beginner in nodejs and angular, I'm trying to upload image using multer and image is uploaded successfully and send response but i can't find the image in the destination folder no moving happens.
I tried those paths for the folder: ./images
../../images but non of them work here is my hierarchy
project hierarchy
var express = require('express');
const router = express.Router();
var multer = require('multer');
var upload = multer({ storage: storage });
// SET STORAGE
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./images")
},
filename: (req, file, cb) => {
cb(null, file.originalname.toLowerCase())
}
})
router.post('/', upload.single('image'), (req, res, next) => {
const file = req.file
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send(file);
})
module.exports = router;
I expected to find the uploaded image in the destination folder but the image isn't moved to it
How can I create a endpoint in node.js (localhost:8000/file) that receives files and stores them somewhere locally.
You can use multer npm module for this
Write a middleware named upload.js in express which will upload your file to your server
upload.js
const multer = require('multer');
const maxSize = 10 * 1024 * 1024;
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads')
},
filename: (req, file, cb) => {
cb(null, file.originalname)
},
});
const upload = multer({
storage: storage
});
module.exports = upload;
This will upload your file to your server.You need to call it in your route
app.js
const upload = require('./upload.js')
router.post("/files", upload.single('file'), (req,res)=>{
console.log("This is file ",req.file)
});
Make a folder named uploads and all files will be in uploads folder.
I am trying to upload image using multer but getting error,uploads is not a function.Here is my code
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single('image'), function(req, res) {
console.log(req.file);
var file = __dirname + '/' + req.file.filename;
uploads(req.file.path, file, function(err) {
if (err) {
console.log(err);
res.send(500);
} else {
res.json({
message: 'File uploaded successfully',
filename: req.file.filename
});
}
});
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single('image'), function(req, res) {
yourModel.create(req.body,function(err,result){
console.log(result);
});
});
Its quite obvious; uploads is not a function but uplaod is. So use
upload.single('image')
As #Kuldeep said you don't have to the uploads(filePath, file, (err) => {...}) inside the route.
When you are using multer as middleware (the middle function) multer will automatically upload the file and expose the filename, originalName etc to req.file object inside the route
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single('image'), function(req, res) {
// here just write the success or error login
});
Reference You can check here: here
EDIT: The above code will upload the file with hex string as filename without any extension.
In order to add rename function you need to use diskStorage. Here is the code taken from this github issue page.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './images/')
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype)); //this is the rename func
});
}
});
var uploads = multer({ storage: storage });
Now you can use the uploads variable as middleware as shown in the above snippet.
I haven't found a great, soup-to-nuts guide on using Multer (the website is just a little lacking for newbies) so here's my stab at it.
After using:
npm install multer --save
to add it to your project.
For me, I wanted to capture files on a specific route, namely:
/customers/:id/upload
So, I went into my customers.js route file and added:
var multer = require('multer');
as well as the code to set up the storage (diskStorage) and filename configuration tweaks:
var storage=multer.diskStorage({
destination: function(req,file,cb){
cb(null,'/uploads/');
},
filename: function(req,file,cb){
cb(null,file.fieldname+'-'+Date.now());
}
});
I could then create the upload middleware object that lets me specify, per route, how I would like Multer to handle file uploads. On the route above, I only want to receive one file with a particular internal filename so my customers.js route file looks like this:
router.post('/:id/targets/upload', upload.single('connections'), function(req,res,next){
console.log("Router:POST: Companies/:_id/upload");
console.log(req.file);
...
});
All of the examples I saw had stuff being added to the app.js file but these seemed a bit awkward and contrived as examples. Every route may have different file handling needs so it just seemed more appropriate, to me, to configure Multer on a per-controller basis. YMMV.
I'm using nodejs as backend and vuejs as front. I've uploaded somes files as test using postman to my backend, but, how could I display these uploaded files using multer?
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
const upload = multer({ storage: storage }).single('logo');
router.post('/logo', auth.authorize, (req, res, next) => {
upload(req, res, (err) => {
});
res.status(200).send('uploaded');
});
I got an image named 'logo-1531296527722' in my api public folder. If I try to use it in my img src (http://localhost:3000/api/company/public/logo-1531296527722) it doesn't displayed. If I try to access this route I got this error Cannot GET /api/company/public/logo-1531296527722. In all questions about that, nodejs has its own html processor like ejs or jade, but I my case, nodejs is just serving my front and all images must be rendered using vuejs.
I dit it!
In my app.js I include app.use('/dist', express.static(path.join(__dirname + '/dist')));
After specifying the path for the uploaded image to ./uploads my images are still going towards tmp folder.
My multer configuration
const multer = require("multer");
const storage = multer.diskStorage({
desitnation: function(req, file, cb){
cb(null, './uploads/');
},
filename: function(req, file, cb){
cb(null, file.originalname);
}
})
const upload = multer({storage: storage});
It seems the spelling desitnation is wrongly spelled. It should be destination.