Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sails.JS File uploads using skipper, accessing original file name and dynamic upload path

I want to upload a simple file using skipper. Earlier, files uploaded via forms could be accessed using req.files but got to know that in Sails 0.10.x, with skipper installed by default, req.files is undefined. Instead of that req.file('filename') is used to access the file.

I could do a simple file upload looking at the documentation. However, I want to be able to access the file name before uploading it and also need to

  • Upload the file to a dynamically created directory based on the user who uploaded it
  • The name of the newly created file should be oldFileName + _ + timestamp in integer

How can I do this using skipper module or rather what is the most efficient way of doing this ?

EDIT
So far I have been able to do this but I am hoping there must be a better way.

For accessing the filename, I used this expression

var inputFileName = req.file('inputFile')._files[0]["stream"]["filename"];

I could see that skipper automatically creates the directory if its not present based on the filepath and name given in the parameter to upload function

like image 587
Mandeep Singh Avatar asked Jul 04 '14 10:07

Mandeep Singh


1 Answers

this is a problem in Skipper at the moment - there a 2 Pull-Requests for this (https://github.com/balderdashy/skipper/issues/12) - but i dont know when this is merged and available.

To solve your Problem to this:

1. Overrwrite filename

// save original file name
var origifile = req.file('testfile')._files[0].stream.filename;
var filename = origifile;

// check if file is existing and change filename if necessary
while(fs.existsSync(".tmp/uploads/" +filename)){
   // Add 4 random chars at he beginning of the filename
   filename = randString(3)+"_"+origifile; 
};

req.file('testfile').upload(filename,function (err, files) {

Attention: You have to write a randString()-Function

2. Move the uploaded file in your folder

In the upload-callback:

fs.rename("/tmp/uploads/"+files[0].filename, "your_folder/" +files[0].filename, function(err){
.... });
like image 190
mdunisch Avatar answered Nov 15 '22 05:11

mdunisch