2014-12-10 16:28:16 +03:00
|
|
|
var config = require('../config'),
|
2014-09-26 17:31:23 +04:00
|
|
|
Promise = require('bluebird'),
|
2014-07-15 14:40:14 +04:00
|
|
|
fs = require('fs-extra'),
|
|
|
|
storage = require('../storage'),
|
|
|
|
errors = require('../errors'),
|
2014-12-10 16:28:16 +03:00
|
|
|
utils = require('./utils'),
|
2014-07-15 14:40:14 +04:00
|
|
|
|
|
|
|
upload;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* ## Upload API Methods
|
|
|
|
*
|
|
|
|
* **See:** [API Methods](index.js.html#api%20methods)
|
|
|
|
*/
|
|
|
|
upload = {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* ### Add Image
|
|
|
|
*
|
|
|
|
* @public
|
|
|
|
* @param {{context}} options
|
|
|
|
* @returns {Promise} Success
|
|
|
|
*/
|
2014-08-17 10:17:23 +04:00
|
|
|
add: function (options) {
|
2014-08-29 07:48:49 +04:00
|
|
|
var store = storage.getStorage(),
|
2014-07-15 14:40:14 +04:00
|
|
|
filepath;
|
|
|
|
|
2014-12-10 16:28:16 +03:00
|
|
|
// Check if a file was provided
|
|
|
|
if (!utils.checkFileExists(options, 'uploadimage')) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(new errors.NoPermissionError('Please select an image.'));
|
2014-07-15 14:40:14 +04:00
|
|
|
}
|
|
|
|
|
2014-12-10 16:28:16 +03:00
|
|
|
// Check if the file is valid
|
|
|
|
if (!utils.checkFileIsValid(options.uploadimage, config.uploads.contentTypes, config.uploads.extensions)) {
|
|
|
|
return Promise.reject(new errors.UnsupportedMediaTypeError('Please select a valid image.'));
|
|
|
|
}
|
|
|
|
|
2014-07-15 14:40:14 +04:00
|
|
|
filepath = options.uploadimage.path;
|
|
|
|
|
2014-12-10 16:28:16 +03:00
|
|
|
return store.save(options.uploadimage).then(function (url) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return url;
|
2014-07-15 14:40:14 +04:00
|
|
|
}).finally(function () {
|
|
|
|
// Remove uploaded file from tmp location
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.promisify(fs.unlink)(filepath);
|
2014-07-15 14:40:14 +04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-08-17 10:17:23 +04:00
|
|
|
module.exports = upload;
|