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

1

7

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

Kilometer answered 4/7, 2014 at 10:41 Comment(0)
S
11

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){
.... });
Spectroscope answered 6/7, 2014 at 7:4 Comment(1)
Thanks, that's what I ended up doing eventually. I am appending a timestamp(integer) suffix at the end of the filename followed by the extension.Kilometer

© 2022 - 2024 — McMap. All rights reserved.