89 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-02-20 15:57:34 +01:00
'use strict';
/**
* Module dependencies
*/
// Public node modules.
2022-01-04 19:21:05 +01:00
const { pipeline } = require('stream');
2018-02-20 15:57:34 +01:00
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();
}
};
2022-02-15 14:20:25 +01:00
// Ensure uploads folder exists
2022-03-14 17:54:35 +01:00
const uploadPath = path.resolve(strapi.dirs.static.public, UPLOADS_FOLDER_NAME);
if (!fse.pathExistsSync(uploadPath)) {
throw new Error(
`The upload folder (${uploadPath}) doesn't exist or is not accessible. Please make sure it exists.`
);
}
2018-02-20 17:10:25 +01:00
return {
2022-01-04 19:21:05 +01:00
uploadStream(file) {
verifySize(file);
return new Promise((resolve, reject) => {
pipeline(
file.stream,
fs.createWriteStream(path.join(uploadPath, `${file.hash}${file.ext}`)),
2022-01-04 19:21:05 +01:00
err => {
if (err) {
return reject(err);
}
file.url = `/uploads/${file.hash}${file.ext}`;
resolve();
}
);
});
},
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) => {
2022-02-21 11:59:30 +01:00
const filePath = path.join(uploadPath, `${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
};