2018-02-20 15:57:34 +01:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Public node modules.
|
|
|
|
const fs = require('fs');
|
|
|
|
const path = require('path');
|
2020-02-26 19:38:23 +01:00
|
|
|
|
2018-02-20 15:57:34 +01:00
|
|
|
module.exports = {
|
2020-02-27 19:34:14 +01:00
|
|
|
init({ sizeLimit = 1000000 } = {}) {
|
2020-02-26 19:38:23 +01:00
|
|
|
const verifySize = file => {
|
|
|
|
if (file.size > sizeLimit) {
|
|
|
|
throw strapi.errors.badRequest('FileToBig', {
|
|
|
|
errors: [
|
|
|
|
{
|
|
|
|
id: 'Upload.status.sizeLimit',
|
|
|
|
message: `${file.name} file is bigger than limit size!`,
|
|
|
|
values: { file: file.name },
|
|
|
|
},
|
|
|
|
],
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2018-02-20 17:10:25 +01:00
|
|
|
return {
|
2020-02-27 19:34:14 +01:00
|
|
|
upload(file) {
|
2020-02-26 19:38:23 +01:00
|
|
|
verifySize(file);
|
|
|
|
|
2018-02-20 15:57:34 +01:00
|
|
|
return new Promise((resolve, reject) => {
|
2018-02-21 17:18:33 +01:00
|
|
|
// write file in public/assets folder
|
2020-02-26 19:38:23 +01:00
|
|
|
fs.writeFile(
|
2020-04-20 10:56:01 +02:00
|
|
|
path.join(strapi.config.paths.static, `/uploads/${file.hash}${file.ext}`),
|
2020-02-26 19:38:23 +01:00
|
|
|
file.buffer,
|
|
|
|
err => {
|
|
|
|
if (err) {
|
|
|
|
return reject(err);
|
|
|
|
}
|
2018-02-20 15:57:34 +01:00
|
|
|
|
2020-02-26 19:38:23 +01:00
|
|
|
file.url = `/uploads/${file.hash}${file.ext}`;
|
2018-02-20 15:57:34 +01:00
|
|
|
|
2020-02-26 19:38:23 +01:00
|
|
|
resolve();
|
|
|
|
}
|
|
|
|
);
|
2018-02-20 15:57:34 +01:00
|
|
|
});
|
|
|
|
},
|
2020-02-27 19:34:14 +01:00
|
|
|
delete(file) {
|
2018-02-20 15:57:34 +01:00
|
|
|
return new Promise((resolve, reject) => {
|
2020-02-26 19:38:23 +01:00
|
|
|
const filePath = path.join(
|
2020-04-20 10:56:01 +02:00
|
|
|
strapi.config.paths.static,
|
2020-02-26 19:38:23 +01:00
|
|
|
`/uploads/${file.hash}${file.ext}`
|
|
|
|
);
|
2018-02-23 14:57:58 +01:00
|
|
|
|
|
|
|
if (!fs.existsSync(filePath)) {
|
2020-02-26 19:38:23 +01:00
|
|
|
return resolve("File doesn't exist");
|
2018-02-23 14:57:58 +01:00
|
|
|
}
|
|
|
|
|
2018-02-21 17:18:33 +01:00
|
|
|
// remove file from public/assets folder
|
2020-02-26 19:38:23 +01:00
|
|
|
fs.unlink(filePath, err => {
|
2018-02-20 15:57:34 +01:00
|
|
|
if (err) {
|
|
|
|
return reject(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
});
|
2020-02-26 19:38:23 +01:00
|
|
|
},
|
2018-02-20 15:57:34 +01:00
|
|
|
};
|
2020-02-26 19:38:23 +01:00
|
|
|
},
|
2018-02-20 15:57:34 +01:00
|
|
|
};
|