67 lines
1.6 KiB
JavaScript
Raw Normal View History

2018-02-20 15:57:34 +01:00
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const fs = require('fs');
const path = require('path');
2022-02-15 14:20:25 +01:00
const fse = require('fs-extra');
2021-10-27 18:54:58 +02:00
const { PayloadTooLargeError } = require('@strapi/utils').errors;
2022-02-15 14:20:25 +01:00
const UPLOADS_FOLDER_NAME = 'uploads';
2018-02-20 15:57:34 +01:00
module.exports = {
init({ sizeLimit = 1000000 } = {}) {
const verifySize = file => {
if (file.size > sizeLimit) {
2021-10-27 18:54:58 +02:00
throw new PayloadTooLargeError();
}
};
const publicDir = strapi.config.get('server.dirs.public');
2022-02-15 14:20:25 +01:00
// Ensure uploads folder exists
const uploadPath = path.resolve(publicDir, UPLOADS_FOLDER_NAME);
fse.ensureDirSync(uploadPath);
2018-02-20 17:10:25 +01:00
return {
upload(file) {
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
2022-02-15 14:20:25 +01:00
fs.writeFile(path.join(uploadPath, `${file.hash}${file.ext}`), file.buffer, err => {
if (err) {
return reject(err);
}
2018-02-20 15:57:34 +01:00
2022-02-15 14:20:25 +01:00
file.url = `/${UPLOADS_FOLDER_NAME}/${file.hash}${file.ext}`;
2018-02-20 15:57:34 +01:00
2022-02-15 14:20:25 +01:00
resolve();
});
2018-02-20 15:57:34 +01:00
});
},
delete(file) {
2018-02-20 15:57:34 +01:00
return new Promise((resolve, reject) => {
const filePath = path.join(publicDir, `/uploads/${file.hash}${file.ext}`);
2018-02-23 14:57:58 +01:00
if (!fs.existsSync(filePath)) {
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
fs.unlink(filePath, err => {
2018-02-20 15:57:34 +01:00
if (err) {
return reject(err);
}
resolve();
});
});
},
2018-02-20 15:57:34 +01:00
};
},
2018-02-20 15:57:34 +01:00
};