How do I get the name of an uploaded file name/path to manipulate it in node.js? I want move the file from the temp folder to a customer folder.
Asked
Active
Viewed 2.7k times
4
-
tampering filesystem from javascript. impossible in normal settings.... – user1655481 Sep 15 '12 at 02:39
2 Answers
7
Node.JS doesn't automatically save uploaded files to disk. You'll instead have to read and parse the multipart/form-data
content yourself via the request's data
and end
events.
Or, you can use a library to do that all for you, such as connect
/express
for its bodyParser
or multipart
middlewares (complete example):
var fs = require('fs');
var express = require('express');
var app = express();
// `bodyParser` includes `multipart`
app.use(express.bodyParser());
app.post('/', function(req, res, next){
// assuming <input type="file" name="upload">
var path = req.files.upload.path;
var name = req.files.upload.name;
// copy...
});
Or use formidable
directly, which connect
uses for the multipart
middleware (complete example).
And, for the // copy...
comment, see How to copy a file?.

Community
- 1
- 1

Jonathan Lonowski
- 121,453
- 34
- 200
- 199
-
I'm confused...everywhere else says 'multipart' is not in bodyParser, but here it says yes? – newman Sep 20 '15 at 17:53
-
@miliu I just haven't updated this answer. At the time this was posted (3 years ago), support for `multipart` was included with the `bodyParser` middleware but has since been removed in favor of other modules dedicated to handling the format, such as [`multer`](https://www.npmjs.org/package/multer) ([mentioned in Express' docs](http://expressjs.com/4x/api.html#req.body)). Another significant change since this post is that Express no longer depends upon Connect. – Jonathan Lonowski Sep 20 '15 at 17:56
-2
app.post('/', function(req, res, next){
var file_name=req.file.filename;
var file_path=req.file.path;
}

Ashutosh Niranjan
- 89
- 7
-
3While this code may answer the question, providing additional context regarding *why* and/or *how* this code answers the question improves its long-term value. – Tân Nov 30 '19 at 12:30