nodejs formidable change filename with timestamp

12.1k views Asked by At

I searched over the internet but I don't find a solution. I use Nodejs Formidable to handle uploaded files ans save it into my API.

All work fine but i want to know how I can change the filename with a unique filename (example: Timestamp) (while maintaining the original file extension).

Here is the code I use :

form.on('end', function (fields, files) {

        var temp_path = this.openedFiles[0].path;
        var file_name = this.openedFiles[0].name;
        var new_location = GLOBAL.config.uploadDir;

        fs.move(temp_path, new_location + file_name, {clobber:true}, function (err) {
            if (err) {
                console.error(err);

                fs.unlink(temp_path, function (err) {
                    if (err) {
                        console.error(err);
                        console.log("TROUBLE deletion temp !");
                    } else {
                        console.log("success deletion temp !");
                    }
                });

            } else {
                res.json('created');
            }
        });
    });

Can any body suggest a solution on this...please?

4

There are 4 answers

0
Pixelight On BEST ANSWER

I found a solution :-) First require path : var path = require('path');

Then I do the trick like this :

var extension = path.extname(this.openedFiles[0].name);
var file_name = new Date().getTime() + extension;

// fs.move from fs-extra move the temp file to destination and unlink it
fs.move(temp_path, new_location + file_name, {clobber:true}, function (err) {
       // Do something     
});
1
Jinceon On

do you mean:
1. you upload a file such as a.txt
2. server store it to /your_path/a_1434449842377.txt

https://www.npmjs.com/package/rename

rename('a.js', function() {
  return {suffix: '-'+Date.now()};
});
// => a-timestamp_of_now.js
0
robertklep On

According to the documentation, you can change the filename that formidable will use to save an upload to.

See here, specifically (emphasis mine):

file.path = null

The path this file is being written to. You can modify this in the 'fileBegin' event in case you are unhappy with the way formidable generates a temporary path for your files.

So try this (untested):

form.on('fileBegin', function(name, file) {
  file.path = '/your/prefered/path/name.ext';
});
0
Michael On

I did this with a little trick and i think it is the easiest way

let myFileName = 'image.png';
myFileName = myFileName.split('.').join('-' + Date.now() + '.');

Then you get as result 'image-1559753269107.png'