arvindr21 / blueimp-file-upload-expressjs

A simple express module for integrating jQuery File Upload.
http://expressjs-fileupload.cloudno.de/
104 stars 69 forks source link

Rename uploaded file #20

Closed Gedzis closed 10 years ago

Gedzis commented 10 years ago

Hi,

Urgent functionality for file upload - file rename. I think it would be great if after file upload you coud rename the file.

arvindr21 commented 10 years ago

@Gedzis Do you have a proposed solution?

Gedzis commented 10 years ago

I think all functionality could be similar to: https://github.com/expressjs/multer/blob/master/index.js

mycaule commented 10 years ago

I think we have to provide an HTTP PUT method on the same URL as the image (just like it was done for fileuploader.delete). We are using the fact that Express framework provide standard handlers for get, put, delete, post.

fileuploader.put = function (req, res, callback) { // do something with req.body.newname and fs.rename }

Then those who want to use the functionnality would have the responsibility to modify the UI-client-side code which involve some basic AJAX request with an input field.

mycaule commented 10 years ago

Similarly, this way is the standard way to provide a REST API for CRUD operations on a database. Create --> HTTP Post Read --> HTTP Get Update --> HTTP Put Delete --> HTTP Delete

Here it's the filesystem instead of a database.

arvindr21 commented 10 years ago

Adding on to @mycaule you can try this

From your express app,

var options = {
   tmpDir: __dirname + '/../public/uploaded/tmp',
   uploadDir: __dirname + '/../public/uploaded/files',
   uploadUrl: '/uploaded/files/',
   storage: {
      type: 'local'
   }
};

var uploader = require('blueimp-file-upload-expressjs')(options);
var fs = require('fs');
var path = require('path');

module.exports = function(router) {
   router.get('/upload', function(req, res) {
      // GET logic
   });
   router.post('/upload', function(req, res) {
      // POST Logic
   });
   router.put('/upload', function(req, res) {
      var oldName = req.body.oldFileName;
      var newName = req.body.newFileName;

      fs.readdir(options.uploadDir, function(err, files) {
         if(err) {
            throw err;
         }
         files.map(function(file) {
            if(file === oldName) {
               console.log('This file will be renamed >> ', file, '<< to >>', newName);
               fs.rename(options.uploadDir + '/' + oldName, options.uploadDir + '/' + newName, function(err, data) {
                  console.log('renamed');
                  res.send('Success');
               });
            }
         })
      });
   });
   router.delete('/uploaded/files/:name', function(req, res) {
      // Delete logic
   });
   return router;
};

Let me know if it works!

Thanks.

arvindr21 commented 10 years ago

Assuming fixed.