0

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.

1 Answer 1

5

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) {
  });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Same thing yet, except now my console.log(data) statement is reading undefined, before it was pulling in the data and listing the chunks.
Ignore my original answer, the information was applied to the wrong part of your code.
Yep, that was it! Thanks for the help! (55 seconds and ill mark it, have a +1 for now)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.