Reputation: 5908
I am working on a Sails.js project at the moment and I would like to upload a file to the server and save the link to that file in my database.
For example, when I click add FILE, it should allow me to select a file from my computer and when I click submit, it should upload the file to the URL that I point ( create the folder if it does not exist).
Can this be accomplished with Sails.js? If yes, how?
Thank you!
Upvotes: 2
Views: 8423
Reputation: 57
The best option is to do this on middleware
aware to check filetypes and route matching otherwise bad actors can upload malicious files
Edit config/http.js like this
serverOptions: {
timeout: 600000,
},
middleware: {
/***************************************************************************
* *
* The order in which middleware should be run for HTTP requests. *
* (This Sails app's routes are handled by the "router" middleware below.) *
* *
***************************************************************************/
order: [
'cookieParser',
'session',
'bodyParser',
'fileUpload', //new middleware
'compress',
'poweredBy',
'router',
'www',
'favicon',
],
fileUpload middleware code
fileUpload: (function () {
return function (req, res, next) {
console.log('Received HTTP request: ' + req.method + ' ' + req.path);
const uploadRoutes = ['/save-user-profile-image'];
if (req.method === 'POST' && uploadRoutes.includes(req.path)) {
req.file('profileImage').upload(
{
maxBytes: 10000000,
dirname: require('path').resolve(sails.config.appPath, 'uploads/'),
saveAs: `YOUR_FILE_NAME.jpg`
},
function (err, files) {
if (err) {
console.log('Error: ' + err.message);
return next(err);
}
if (files.length > 0) {
var uploadedFile = files[0];
var fileName = uploadedFile.filename;
var sizeInBytes = uploadedFile.size;
var path = uploadedFile.fd;
req.body.fileName = fileName;
req.body.sizeInBytes = sizeInBytes;
req.body.filePath = path;
req.body.imageName = name;
}
return next();
}
);
} else {
return next();
}
};
})(),
Upvotes: 0
Reputation: 3736
This blog has has a good example of handling a file upload--it worked for me:
http://maangalabs.com/blog/2014/08/12/uploading-a-file-in-sails/
upload: function (req, res) {
// Call to /upload via GET is error
if(req.method === 'GET')
return res.json({'status':'GET not allowed'});
var uploadFile = req.file('uploadFile');
console.log(uploadFile);
uploadFile.upload(function onUploadComplete(err, files) {
// Files will be uploaded to .tmp/uploads
// IF ERROR Return and send 500 error with error
if (err) return res.serverError(err);
console.log(files);
res.json({status:200,file:files});
});
}
Upvotes: 2
Reputation: 2049
This will get you most of the way there: https://github.com/balderdashy/sails/issues/27
You can use https://github.com/aconbere/node-file-utils to create directories, etc. Install it with
npm install file
Require file in the module having code similar to that in .../sails/issue/27.
Upvotes: 5