1

I am using multer and fs to upload an image file How do I change the directory of uploaded file,since all files are stored my "routes" folder rather than "uploads" created by multer Also,how can i change name file EXAMPLE :

username.jpg

this is my code:

var upload = multer({ dest: '/tmp' }); router.post('/file_upload', upload.single("file"), function (req, res) { var file = __dirname + "/" + req.file.originalname; fs.readFile(req.file.path, function (err, data) { fs.writeFile(file, data, function (err) { if (err) { console.log(err); } else { res.redirect("back"); } }); }); }) 

On client Side:

<html> <head> <title>File Uploading Form</title> </head> <body> <h3>File Upload:</h3> Select a file to upload: <br /> <form action="/file_upload" method="POST" enctype="multipart/form- data"> <input type="file" name="file" /> <input type="submit" value="Upload File" /> </form> </body> </html> 

3 Answers 3

1

I'd do it as follows, unless you need to keep the uploaded file in its original upload location:

var upload = multer({ dest: '/tmp' }); router.post('/file_upload', upload.single('file'), function (req, res) { // Here change 'uploads' to the folder name you prefer. // Also change req.file.originalname for your preferred file name var file = path.join(__dirname, 'uploads', req.file.originalname) fs.rename(req.file.path, file, function (err) { if (err) { console.log(err); } else { res.redirect("back") } }) }) 
Sign up to request clarification or add additional context in comments.

Comments

1

Declare your directory in storage variable

var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './')//Declare it here where you want to store }, filename: function (req, file, cb) { cb(null, file.originalname);//You can give name here file.**** } }); var upload = multer({ storage: storage }); 

while handling post request

var path = req.files[0].path; var imageName = req.files[0].originalname;//change name here var imagepath = {}; imagepath['path'] = path; imagepath['originalname'] = imageName; // name change 

Comments

0

Isn't your variable file specifying where you are writing to your file?

var file = __dirname + "/NewFolder/" + newFileName.jpg 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.