-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument-type-detector.js
More file actions
75 lines (67 loc) · 2.32 KB
/
document-type-detector.js
File metadata and controls
75 lines (67 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Document Type Detector Module
* Handles detection of document types based on binary signatures
*/
const DocumentTypeDetector = {
/**
* Detect the MIME type of a document from its binary content
* @param {ArrayBuffer} buffer - Raw document data
* @returns {Object} Object with mimeType and extension
*/
detectType: function(buffer) {
const byteArray = new Uint8Array(buffer);
// Check for PDF
if (byteArray.length > 4 &&
byteArray[0] === 0x25 && byteArray[1] === 0x50 &&
byteArray[2] === 0x44 && byteArray[3] === 0x46) {
return {
mimeType: "application/pdf",
extension: "pdf"
};
}
// Check for JPEG
if (byteArray.length > 2 &&
byteArray[0] === 0xFF && byteArray[1] === 0xD8) {
return {
mimeType: "image/jpeg",
extension: "jpg"
};
}
// Check for PNG
if (byteArray.length > 8 &&
byteArray[0] === 0x89 && byteArray[1] === 0x50 &&
byteArray[2] === 0x4E && byteArray[3] === 0x47 &&
byteArray[4] === 0x0D && byteArray[5] === 0x0A &&
byteArray[6] === 0x1A && byteArray[7] === 0x0A) {
return {
mimeType: "image/png",
extension: "png"
};
}
// Check for XML
if (byteArray.length > 5 &&
byteArray[0] === 0x3C && byteArray[1] === 0x3F &&
byteArray[2] === 0x78 && byteArray[3] === 0x6D &&
byteArray[4] === 0x6C) {
return {
mimeType: "application/xml",
extension: "xml"
};
}
// Check for DOCX/XLSX (Office Open XML)
if (byteArray.length > 4 &&
byteArray[0] === 0x50 && byteArray[1] === 0x4B &&
byteArray[2] === 0x03 && byteArray[3] === 0x04) {
return {
mimeType: "application/vnd.openxmlformats-officedocument",
extension: "docx"
};
}
// Default to binary
return {
mimeType: "application/octet-stream",
extension: "bin"
};
}
};
window.DocumentTypeDetector = DocumentTypeDetector;