SHARE
TWEET

Untitled

a guest Jun 25th, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var uuid = require('node-uuid'),
  2.     path = require('path'),
  3.     blobAdapter = require('skipper-disk');
  4.  
  5. module.exports = {
  6.  
  7.   upload: function(req, res) {
  8.  
  9.     var receiver = blobAdapter().receive({
  10.           dirname: sails.config.appPath + "/public/files/",
  11.           saveAs: function(file) {
  12.             var filename = file.filename,
  13.                 newName = uuid.v4() + path.extname(filename);
  14.             return newName;
  15.           }
  16.         }),
  17.         results = [];
  18.  
  19.     req.file('docs').upload(receiver, function (err, files) {
  20.       if (err) return res.serverError(err);
  21.       async.forEach(files, function(file, next) {
  22.         Document.create({
  23.           name: file.filename,
  24.           size: file.size,
  25.           localName: // ***** how do I get the `saveAs()` value from the uploaded file *****,
  26.           path: // *** and likewise how do i get the path ******
  27.         }).exec(function(err, savedFile){
  28.           if (err) {
  29.             next(err);
  30.           } else {
  31.             results.push({
  32.               id: savedFile.id,
  33.               url: '/files/' + savedFile.localName
  34.             });
  35.             next();
  36.           }
  37.         });
  38.       }, function(err){
  39.         if (err) {
  40.           sails.log.error('caught error', err);
  41.           return res.serverError({error: err});
  42.         } else {
  43.           return res.json({ files: results });
  44.         }
  45.       });
  46.     });
  47.   },
  48.  
  49.   _config: {}
  50.  
  51. };
  52.      
  53. // Uploader utilities and helper methods
  54. // designed to be relatively generic.
  55.  
  56. var fs = require('fs'),
  57.     Writable = require('stream').Writable;
  58.  
  59. exports.documentReceiverStream = function(options) {
  60.   var defaults = {
  61.     dirname: '/dev/null',
  62.     saveAs: function(file){
  63.       return file.filename;
  64.     },
  65.     completed: function(file, done){
  66.       done();
  67.     }
  68.   };
  69.  
  70.   // I don't have access to jQuery here so this is the simplest way I
  71.   // could think of to merge the options.
  72.   opts = defaults;
  73.   if (options.dirname) opts.dirname = options.dirname;
  74.   if (options.saveAs) opts.saveAs = options.saveAs;
  75.   if (options.completed) opts.completed = options.completed;
  76.  
  77.   var documentReceiver = Writable({objectMode: true});
  78.  
  79.   // This `_write` method is invoked each time a new file is received
  80.   // from the Readable stream (Upstream) which is pumping filestreams
  81.   // into this receiver.  (filename === `file.filename`).
  82.   documentReceiver._write = function onFile(file, encoding, done) {
  83.     var newFilename = opts.saveAs(file),
  84.         fileSavePath = opts.dirname + newFilename,
  85.         outputs = fs.createWriteStream(fileSavePath, encoding);
  86.     file.pipe(outputs);
  87.  
  88.     // Garbage-collect the bytes that were already written for this file.
  89.     // (called when a read or write error occurs)
  90.     function gc(err) {
  91.       sails.log.debug("Garbage collecting file '" + file.filename + "' located at '" + fileSavePath + "'");
  92.  
  93.       fs.unlink(fileSavePath, function (gcErr) {
  94.         if (gcErr) {
  95.           return done([err].concat([gcErr]));
  96.         } else {
  97.           return done(err);
  98.         }
  99.       });
  100.     };
  101.  
  102.     file.on('error', function (err) {
  103.       sails.log.error('READ error on file ' + file.filename, '::', err);
  104.     });
  105.  
  106.     outputs.on('error', function failedToWriteFile (err) {
  107.       sails.log.error('failed to write file', file.filename, 'with encoding', encoding, ': done =', done);
  108.       gc(err);
  109.     });
  110.  
  111.     outputs.on('finish', function successfullyWroteFile () {
  112.       sails.log.debug("file uploaded")
  113.       opts.completed({
  114.         name: file.filename,
  115.         size: file.size,
  116.         localName: newFilename,
  117.         path: fileSavePath
  118.       }, done);
  119.     });
  120.   };
  121.  
  122.   return documentReceiver;
  123. }
  124.      
  125. var uuid = require('node-uuid'),
  126.     path = require('path');
  127.  
  128. module.exports = {
  129.  
  130.   upload: function(req, res) {
  131.  
  132.     var results = [],
  133.         streamOptions = {
  134.           dirname: sails.config.appPath + "/public/files/",
  135.           saveAs: function(file) {
  136.             var filename = file.filename,
  137.                 newName = uuid.v4() + path.extname(filename);
  138.             return newName;
  139.           },
  140.           completed: function(fileData, next) {
  141.             Document.create(fileData).exec(function(err, savedFile){
  142.               if (err) {
  143.                 next(err);
  144.               } else {
  145.                 results.push({
  146.                   id: savedFile.id,
  147.                   url: '/files/' + savedFile.localName
  148.                 });
  149.                 next();
  150.               }
  151.             });
  152.           }
  153.         };
  154.  
  155.     req.file('docs').upload(Uploader.documentReceiverStream(streamOptions),
  156.       function (err, files) {
  157.         if (err) return res.serverError(err);
  158.  
  159.         res.json({
  160.           message: files.length + ' file(s) uploaded successfully!',
  161.           files: results
  162.         });
  163.       }
  164.     );
  165.   },
  166.  
  167.   _config: {}
  168. };
  169.      
  170. req.file('fileTest').upload({
  171.   // You can apply a file upload limit (in bytes)
  172.   maxBytes: maxUpload,
  173.   adapter: require('skipper-disk')
  174. }, function whenDone(err, uploadedFiles) {
  175.   if (err) {
  176.     var error = {  "status": 500, "error" : err };
  177.     res.status(500);
  178.     return res.json(error);
  179.   } else {
  180.     for (var u in uploadedFiles) {
  181.       //"fd" contains the actual file path (and name) of your file on disk
  182.       fileOnDisk = uploadedFiles[u].fd;
  183.       // I suggest you stringify the object to see what it contains and might be useful to you
  184.       console.log(JSON.stringify(uploadedFiles[u]));
  185.     }
  186.   }
  187. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top