-
-
Notifications
You must be signed in to change notification settings - Fork 683
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to detect the file type? #387
Comments
@gknpezgssb hi there. You can use the Let us know if you need more help. We are looking to improve the docs. edit: example form.on('file', function (name, file) {
console.log(name) // => string
console.log(file) // => object
console.log(file.type) // => mime type
}) Or the other variant is if you can check it from the |
@olstenlarck the |
I have found my solution. Thanks
|
Good point. Hm, probably it's better to use the .on('part'). It is the same but I more like that api. |
but there is no |
ha, strange! my fault haha |
Agree with @olstenlarck. The correct place to do all validations (as soon as possible) is in form.onPart(). form.onPart = function (part) {
if (part.filename) {
if (isInvalidFileName(part.filename) || isInvalidMimeType(part.mime)) {
res.sendStatus(400);
}
}
} |
@olstenlarck, you added there "docs" tag. Does it need something to document? Or it was back then when there was no "question" tag? P.S. If there's no need to document it, then lets close it. Otherwise, lets create another issue for documenting, and then close this. |
Re-reading the thread... and realizing that i still promote
@DennisJames that's totally another issues - probably the most talked - more functionality in the "before saving to disk" step. @xarguments, yes, it was before the question label. And it's always good thing to add docs. Or at least add such code snippets in the readme. Or probably what about
|
Should I be able to use form.onPart() along with form.parse() in order to form.onPart(): test for valid file types and return validation message if that fails or continue on to... form.parse(): parse the file if the validation in form.onPart() passes? I can't seem to find the right way to do this. CONTROLLER:
SERVICE/formidable parse wrapper:
|
you can use |
This is how I solve it. In this way, I can keep using I don't test it how it works with base64 encoding, so use on own risk import formidable from 'formidable';
import { fileTypeFromBuffer, supportedMimeTypes } from 'file-type';
export function formidableWithAnalyzing(options = {}) {
const form = formidable(options);
// The minimum to catch file header
const minimumBytes = 4100;
// Assign fieldName
form.on('fileBegin', (fieldName, file) => {
file.fieldName = fieldName;
});
form.onPart = function (part) {
// Run analyzing only for supported types
// just the way to exclude text/*
part.mimetypeAnalyzing = (
part.mimetype === 'application/octet-stream' ||
supportedMimeTypes.has(part.mimetype)
);
part.mimetypeDetected = false;
part.mimetypeOriginal = part.mimetype;
part.mimetypeValid = false;
if (!part.mimetypeAnalyzing) {
form._handlePart(part);
return;
}
const encoding = part.transferEncoding === 'utf-8' ? 'utf8' : 'binary';
let cacheBuffer = Buffer.alloc(0, 0, encoding);
let partEnd = false;
let partAnalyzing = false;
const catchUpEnd = () => {
if (!partEnd) return;
part.emit('end');
};
const catchUpBuffer = () => {
if (cacheBuffer) {
part.emit('data', cacheBuffer);
cacheBuffer = undefined;
}
};
part.on('end', onPartEnd);
part.on('data', onPartData);
function onPartEnd() {
partEnd = true;
// Not reached minimum bytes, so let's try to analyze what we have
if (!partAnalyzing) {
partAnalyzing = true;
analyzeFileType();
}
}
function onPartData(chunk) {
if (chunk.length > 0) {
cacheBuffer = Buffer.concat([cacheBuffer, chunk]);
}
if (!partAnalyzing && cacheBuffer.length >= minimumBytes) {
partAnalyzing = true;
analyzeFileType();
}
}
function analyzeFileType() {
form.pause();
form._flushing += 1; // pause end trigger
const analyzing = cacheBuffer
? fileTypeFromBuffer(cacheBuffer)
: Promise.resolve(null);
analyzing
.then((r) => {
if (r?.mime) {
part.mimetypeDetected = true;
part.mimetypeValid = part.mimetypeOriginal === r.mime;
part.mimetype = r.mime; // replce it to keep use in filter options.
}
// De-attach our handlers
part.off('data', onPartData);
part.off('end', onPartEnd);
// Setup native handlers
form._flushing -= 1;
form._handlePart(part);
form.resume();
// Catch-up data
catchUpBuffer();
// Catch-up end event
catchUpEnd();
})
.catch((err) => {
console.error('Error occurred while file mimetype analyzing', err);
// Throw error on global level
form._error(
new FormidableError(
'Failed to parse file content type',
errors.pluginFailed,
400,
),
);
});
}
};
return form;
} On my project, i need extra support of function filter(part) {
const {
mimetype,
mimetypeValid,
mimetypeOriginal,
mimetypeDetected,
mimetypeAnalyzing
} = part;
// Seems user uploaded the file with an incorrect file extension.
if (mimetypeAnalyzing && !mimetypeValid) {
return false;
}
return true;
} |
To detecting whether the uploaded file type is jpg / png or not,if not throw an ERROR.
which API should I use and how?
The text was updated successfully, but these errors were encountered: