Reputation: 104785
I'm working on creating a simple file uploader on a node server with expressjs as the middleware. So far, the server side looks like:
app.post('/upload', function(req, res) {
console.log(req.files);
//Handle the file
fs.readFile(req.files.imageUploader.path, function(err, data) {
var newPath = __dirname;
console.log(newPath);
console.log(data);
fs.writeFile(newPath, data, function(err) {
console.log(err);
res.send("AOK");
});
});
});
Now, the log statement for __dirname
is my source directory, as expected (C:\Development\GitHub\ExpressFileUpload), however an error is happening on the upload:
{ [Error: EISDIR, open 'C:\Development\GitHub\ExpressFileUpload']
errno: 28,
code: 'EISDIR',
path: 'C:\\Development\\GitHub\\ExpressFileUpload' }
I've tried changing the newPath
to be /
and ./
but no change, different errors, but still errors. Is it something to do with the double \\
in the path
in the error? Am I missing something simple here? Thanks for the help, let me know if more info is needed.
Upvotes: 0
Views: 2704
Reputation: 91799
The __dirname
global object is a directory, not a file. Therefore, you can't open it for writing, which is what fs.writeFile()
attempts to do in your script, hence the reason you are getting a EISDIR
. Assuming you want the file to be written with the same name it was uploaded with, you can do this:
var file = req.files.imageUploader;
fs.readFile(file.path, function(err, data) {
var path = __dirname + '/' + file.name;
fs.writeFile(path, data, function(err) {
});
});
Upvotes: 5