aguidrevitch / jquery-file-upload-middleware

jQuery-File-Upload Express.js middleware
294 stars 120 forks source link

Rename files #8

Open ghost opened 11 years ago

ghost commented 11 years ago

Is it possible to rename files before responding to the client? Thus, when I do something like:

upload.on "end", (fileinfo) ->
  console.log fileinfo

fileinfo's name is a rename one and NOT the original file's names!

Thank you!

aguidrevitch commented 11 years ago

I can add a hook (callback) which will be called before sending file, but not in 0.0.6. Will it work for you ? What problem are you trying to solve ?

ghost commented 11 years ago

I need to give the files a uuid. I'm not interested in keeping te original name!

I found a workaround for now, but it's convoluted! So any built-in hook is more than welcome ^^

aguidrevitch commented 11 years ago

Actually, due to the nature of nodejs' EventEmitter, you can modify fileInfo in 'end' event handler. I've checked EventEmitter's code and tried myself - it should work. Can you please give it a try ?

bbbmmmlll commented 11 years ago

This works for me:

  upload.on('begin', function (fileInfo) {      
    var ext = fileInfo.name.substr(fileInfo.name.lastIndexOf('.') + 1);
    var shortid = shortID();
    fileInfo.name = shortid + '.' + ext;
  });
xiangpaopao commented 10 years ago

@bbbmmmlll It's good

flaudre commented 8 years ago

I spent quite an amount of time in order to find out how to rename the files and then move them to another folder, here's the final implementation:

// File Upload
upload.configure({
    uploadDir: __dirname + '/../public/uploads',
    uploadUrl: '/uploads',
    imageVersions: {
            thumbs: {
                  width: 80,
                  height: 80
            }
    }
});

router.use('/admin/upload', upload.fileHandler());

upload.on('begin', function(fileInfo){
    // Create crypto filename
    crypto.pseudoRandomBytes(16, function (err, raw) {
        if(err) { console.log(err); }

        fileInfo.name = raw.toString('hex') + path.extname(fileInfo.originalName);

    });
})

upload.on('end', function(fileInfo){
        // Move to proper directory
        upload.fileManager().move(fileInfo.name, '../images/galery', function(err, result){
                if(err){ console.log(err); }
        });
});
Zenfeder commented 8 years ago

@flaudre nice!