file name is too big

This commit is contained in:
Marc-Roig 2022-09-23 14:44:20 +02:00
parent dbd85eef4f
commit ac79c07b59
3 changed files with 23 additions and 6 deletions

View File

@ -3,7 +3,7 @@
const { PayloadTooLargeError } = require('@strapi/utils/lib/errors');
const _ = require('lodash');
const registerUploadMiddleware = require('./middlewares/upload');
const { kbytesToBytes } = require('./utils/file');
const { kbytesToBytes, bytesToHumanReadable } = require('./utils/file');
/**
* Register upload plugin
@ -76,7 +76,9 @@ const baseProvider = {
},
checkFileSize(file, { sizeLimit }) {
if (sizeLimit && kbytesToBytes(file.size) > sizeLimit) {
throw new PayloadTooLargeError();
throw new PayloadTooLargeError(
`${file.name} exceeds size limit of ${bytesToHumanReadable(sizeLimit)}.`
);
}
},
};

View File

@ -5,8 +5,14 @@
*/
const { Writable } = require('stream');
const bytesToKbytes = (bytes) => Math.round((bytes / 1000) * 100) / 100;
const kbytesToBytes = (kbytes) => kbytes * 1000;
const bytesToKbytes = (bytes) => Math.round((bytes / 1000) * 100) / 100;
const bytesToHumanReadable = (bytes) => {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
if (bytes === 0) return '0 Bytes';
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1000)), 10);
return `${Math.round(bytes / 1000 ** i, 2)} ${sizes[i]}`;
};
const streamToBuffer = (stream) =>
new Promise((resolve, reject) => {
@ -46,6 +52,7 @@ function writableDiscardStream(options) {
module.exports = {
streamToBuffer,
bytesToHumanReadable,
bytesToKbytes,
kbytesToBytes,
getStreamSize,

View File

@ -10,7 +10,7 @@ const fs = require('fs');
const path = require('path');
const fse = require('fs-extra');
const { PayloadTooLargeError } = require('@strapi/utils/lib/errors');
const { kbytesToBytes } = require('../../../core/upload/server/utils/file');
const { kbytesToBytes, bytesToHumanReadable } = require('../../../core/upload/server/utils/file');
const UPLOADS_FOLDER_NAME = 'uploads';
@ -35,9 +35,17 @@ module.exports = {
checkFileSize(file, { sizeLimit } = {}) {
// TODO V5: remove providerOptions sizeLimit
if (providerOptionsSizeLimit) {
if (kbytesToBytes(file.size) > providerOptionsSizeLimit) throw new PayloadTooLargeError();
if (kbytesToBytes(file.size) > providerOptionsSizeLimit)
throw new PayloadTooLargeError(
`${file.name} exceeds size limit of ${bytesToHumanReadable(
providerOptionsSizeLimit
)}.`
);
} else if (sizeLimit) {
if (kbytesToBytes(file.size) > sizeLimit) throw new PayloadTooLargeError();
if (kbytesToBytes(file.size) > sizeLimit)
throw new PayloadTooLargeError(
`${file.name} exceeds size limit of ${bytesToHumanReadable(sizeLimit)}.`
);
}
},
uploadStream(file) {