I am currently using the following code to upload a file by using multer (is a node. js middleware for handling multipart/form-data), but currently I am uploading files to the uploads folder in the js node project.
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads')
},
filename: function(req, file, callback) {
var id_photo = uuidv1();
callback(null, id_photo + "-" + file.originalname);
}
})
Now I need to upload the file to folder ABC not upload to folder uploads, through the link provided
for example http://nanana.com/abc
ABC is the name of the folder where I want to fill the file
you have to install first the fs-extra which will create folder here i am creating folder on bases of id in params you can do same like this
create seprate folder for multer like multerHelper.js
const multer = require('multer');
let fs = require('fs-extra');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
let Id = req.params.id;
let path = `tmp/daily_gasoline_report/${Id}`;
fs.mkdirsSync(path);
cb(null, path);
},
filename: function (req, file, cb) {
// console.log(file);
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.fieldname + '-' + Date.now() + "." + extension);
}
})
let upload = multer({ storage: storage });
let createUserImage = upload.array('images', 100);
let multerHelper = {
createUserImage,
}
module.exports = multerHelper;
in your routes import multerhelper file
const multerHelper = require("../helpers/multer_helper");
router.post(multerHelper , function(req, res, next) {
//Here accessing the body datas.
})
Related
Multer cannot store the file, where the destination is in public/my-uploads
const express = require('express');
const app = express();
const multer = require('multer');
let storage = multer.diskStorage({
destination: '/public/my-uploads',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
const upload = multer({dest:'storage/'}).single('file');
app.post('/upload', upload, (req , res) => {
console.log(req.files) // this does log the uploaded image data.
})
Try this File Storage For Save image in Local
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(
null,
new Date().toISOString().replace(/:/g, "-") + "-" + file.originalname
);
},
});
This happens because you are using windowsOS and where you learned it may be using macOS in windows Path have to setted as mentioned in the above code.
You simply set the file name as given in my answer and destination is root dir "./images"...
This is my multer code to upload multiple files.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/files/'+ req.user.id)
},
filename: function (req, file, cb) {
x = file.originalname; //+path.extname(file.originalname);
cb(null,x);
}
});
var upload = multer({storage: storage});
This is the post request where files get submitted on click submit.
router.post(upload.array("FileUpload",12), function(req, res, next) {
//Here accessing the body datas.
})
So what I want is that, I want to create a folder first with the name of the ID generated which can be access from the req.body and then upload those files into that folder respectively.
But since I cannot access the body first before upload I am unable to create that respective folder directory. Is there any other way around which I can think of and implement this?
Updated Solution using fs-extra package.
const multer = require('multer');
let fs = require('fs-extra');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
let Id = req.body.id;
fs.mkdirsSync('./public/files/'+ req.user.id + '/' + Id);
cb(null, './public/files/'+ req.user.id + '/' + Id)
},
filename: function (req, file, cb) {
x = file.originalname; //+path.extname(file.originalname);
cb(null,x);
}
});
var upload = multer({storage: storage});
This is the post request where files get submitted on click submit.
router.post(upload.array("FileUpload",12), function(req, res, next) {
//Here accessing the body datas.
})
you have to install first the fs-extra which will create folder
create seprate folder for multer like multerHelper.js
const multer = require('multer');
let fs = require('fs-extra');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
fs.mkdirsSync(path);
cb(null, path);
},
filename: function (req, file, cb) {
// console.log(file);
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.fieldname + '-' + Date.now() + "." + extension);
}
})
let upload = multer({ storage: storage });
let createUserImage = upload.array('images', 100);
let multerHelper = {
createUserImage,
}
module.exports = multerHelper;
in your routes import multerhelper file
const multerHelper = require("../helpers/multer_helper");
router.post(multerHelper , function(req, res, next) {
//Here accessing the body datas.
})
I'm using a multer api, and I'm saving files in memory, because I need to upload images and pdf, and I need to process the images.
I can upload images, but I can't upload pdfs files.
Thanks
well, this is my code... I really hope to help you.
const express = require('express');
const multer = require('multer');
const app = express();
const storage =
multer.diskStorage({
destination: path.join(__dirname, 'public/img/'), // destination folder
filename: (req, file, cb) => {
cb(null, uuid.v4() + path.extname(file.originalname));
}
});
const upload =
multer({
storage,
dest: path.join(__dirname, 'public/img/'), // destination folder
limits: {fileSize: 3500000}, // size we will acept, not bigger
fileFilter: (req, file, cb) => {
const filetypes = /jpeg|jpg|png|gif|pdf/; // filetypes you will accept
const mimetype = filetypes.test(file.mimetype); // verify file is == filetypes you will accept
const extname = filetypes.test(path.extname(file.originalname)); // extract the file extension
// if mimetype && extname are true, then no error
if(mimetype && extname){
return cb(null, true);
}
// if mimetype or extname false, give an error of compatibilty
return cb("The uploaded file, isn't compatible :( we're sorry");
}
}).single('image'); // This is the field where is the input type="file", we only accept 1 image
app.use(upload);
and the view will looks like this
app.post('/add', async (req, res) => {
const { originalname, mimetype, destination, filename, path, size} = req.file;
const newImage = {
originalname,
mimetype,
destination,
filename,
path,
size
};
await pool.query('Insert Into imagen set ?', [newImage]);
res.send('image uploaded');
});
this might help you
// Set storage engine
const storage = multer.diskStorage({
destination: "./uploads",
filename: function(req, file, cb) {
// null as first argument means no error
cb(null, Date.now() + "-" + file.originalname);
},
});
let encode_file = null;
let fileName = "";
if (req.file) {
fileName = req.file.originalname;
var filepath = path.join(__dirname, req.file.path);
console.log(filepath);
var stream = fs.readFileSync(filepath);
encode_file = stream.toString("base64");
}
I want to upload a zip file into the server using node.So can any one help me to figure it out.
First upload your zip file using Multer:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
Then unzip it using unzipper module:
1) Install unzipper module
npm i unzipper
2) ExtractZip.js JavaScript
const unzipper = require('./unzip');
var fs = require('fs');
fs.createReadStream('path/to/archive.zip')
.pipe(unzipper.Parse())
.on('entry', function (entry) {
const fileName = entry.path;
const type = entry.type; // 'Directory' or 'File'
const size = entry.vars.uncompressedSize; // There is also compressedSize;
if (fileName === "this IS the file I'm looking for") {
entry.pipe(fs.createWriteStream('output/path'));
} else {
entry.autodrain();
}
});
// Source
Test:
c:\Samim>node ExtractZip.js
You can try multer
npm install --save multer
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
I am a novice at NodeJS and I created a service to upload images to a shared location. However, I need to set the upload folder dynamically based on the user id: for e.g. the folder will be /uploads/{userid}/file.txt
I am not sure how to do it and I have been searching today with no luck.
The NodeJS service looks like:
var express = require('express')
var multer = require('multer')
var Storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "./Uploads");
},
filename: function (req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" +
file.originalname);
}
});
var upload = multer({ Storage: Storage })
var app = express()
app.post('/upload', upload.array('uploads[]', 12), function (req, res, next)
{
return res.end("Files uploaded sucessfully!.");
})
Thank you for the help.
Try this
app.use(multer({
dest: './uploads/',
"rename" : function (fieldname, filename, req, res) {
return path.join(fieldname, req.params.user_id+".txt");
}
})