Skip to content

Instantly share code, notes, and snippets.

@tkh44
Last active March 10, 2020 09:04
Show Gist options
  • Star 52 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save tkh44/8225384 to your computer and use it in GitHub Desktop.
Save tkh44/8225384 to your computer and use it in GitHub Desktop.
Simple file upload for sails.js

Setup

cd /your/project/dir

sails generate controller upload upload

sails generate file get

npm install shortid mkdirp -D
module.exports = {
get: function (req, res) {
res.sendfile(req.path.substr(1));
},
_config: {
rest: false,
shortcuts: false
}
};
module.exports.routes = {
'/': {
view: 'home/index'
},
'get /public/images/*': {
controller: 'FileController',
action: 'get'
}
};
<form id="uploadForm"
enctype="multipart/form-data"
action="/upload/upload"
method="post">
<input type="file" id="userPhotoInput" name="userPhoto" />
</form>
var sid = require('shortid');
var fs = require('fs');
var mkdirp = require('mkdirp');
//var io = require('socket.io');
var UPLOAD_PATH = 'public/images';
// Setup id generator
sid.characters('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$@');
sid.seed(42);
function safeFilename(name) {
name = name.replace(/ /g, '-');
name = name.replace(/[^A-Za-z0-9-_\.]/g, '');
name = name.replace(/\.+/g, '.');
name = name.replace(/-+/g, '-');
name = name.replace(/_+/g, '_');
return name;
}
function fileMinusExt(fileName) {
return fileName.split('.').slice(0, -1).join('.');
}
function fileExtension(fileName) {
return fileName.split('.').slice(-1);
}
// Where you would do your processing, etc
// Stubbed out for now
function processImage(id, name, path, cb) {
console.log('Processing image');
cb(null, {
'result': 'success',
'id': id,
'name': name,
'path': path
});
}
module.exports = {
upload: function (req, res) {
var file = req.files.userPhoto,
id = sid.generate(),
fileName = id + "." + fileExtension(safeFilename(file.name)),
dirPath = UPLOAD_PATH + '/' + id,
filePath = dirPath + '/' + fileName;
try {
mkdirp.sync(dirPath, 0755);
} catch (e) {
console.log(e);
}
fs.readFile(file.path, function (err, data) {
if (err) {
res.json({'error': 'could not read file'});
} else {
fs.writeFile(filePath, data, function (err) {
if (err) {
res.json({'error': 'could not write file to storage'});
} else {
processImage(id, fileName, filePath, function (err, data) {
if (err) {
res.json(err);
} else {
res.json(data);
}
});
}
})
}
});
},
/**
* Overrides for the settings in `config/controllers.js`
* (specific to GifController)
*/
_config: {}
};
@jdcauley
Copy link

jdcauley commented Jan 8, 2014

Can you give me any advice or idea how to save the image path to a full model?

@anhnt
Copy link

anhnt commented Jan 14, 2014

nice post

@onluiz
Copy link

onluiz commented Mar 4, 2014

Thank you, great post =)

@junaidurfjd
Copy link

Assets are loaded once when the server is lifted.. Do we have to "RELIFT" the server in order to access the uploaded images..?

@mgenev
Copy link

mgenev commented Dec 11, 2014

what is npm install -D can't find it in the docs

@daywong1119
Copy link

I am quite new to sails.js, and this example is really awesome. i had a little problem base on this example.
How to get fields value within the same upload form. I tried both "req.body" and "req.params", it dosen't seems work, eg

<form id="uploadForm" enctype="multipart/form-data" action="/media/upload" method="post">
      <input type="file" name="uploadFile" />
      <input type="text" name="name" id="name" placeholder="Name" />
      <input type="submit" value="submit"/>
</form>

@0x80
Copy link

0x80 commented Jan 27, 2015

I don't think this is a good example. Maybe it was in an older version of Sails, but I believe this example is now the proper way to handle uploads.

@jamilnyc
Copy link

jamilnyc commented May 5, 2016

@0x80

What is the major difference between the one here and the one you suggest? Unless I'm missing something, they look pretty similar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment