Read file content from a form upload file

Viewed 313

I use the following code to read the get files from the file system The code is from a blog post called Building a File Uploader with NodeJs.

I was able to see the UI, etc when I ran my project.

I cannot use the following code since I don't have an uploads folder in my project (form.uploadDir)

app.post('/upload', function(req, res){

    // create an incoming form object
    var form = new formidable.IncomingForm();

    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;

    // store all uploads in the /uploads directory - cannot use it
    //form.uploadDir = path.join(__dirname, '/uploads');

    // every time a file has been uploaded successfully,
    // rename it to it's original name
    form.on('file', function(field, file) {
        fs.rename(file.path, path.join(form.uploadDir, file.name));
    });

    // log any errors that occur
    form.on('error', function(err) {
        console.log('An error has occurred: \n' + err);
    });

    // once all the files have been uploaded, send a response to the client
    form.on('end', function() {
        res.end('success');
    });
    // parse the incoming request containing the form data
    form.parse(req);

});

My question is how should I get the file from the UI with the code above? I need to get the file content from the form when I choose my file.

The application is deployed to the cloud and when I use localhost, I use the following code (which works)

const readStream = fs.createReadStream("./file.html");

...

const writeStream = sftp.createWriteStream("/index.html");

...

readStream.pipe(writeStream);

Which creates a file from the file system with the correct path and overwrites it with another file (like here index.html).

1 Answers

As @aedneo said, when the user choose file the file is created in the upload folder , I just needed to rename it and give the right path to the write stream method and it works!

Related