Reputation: 15002
I got this array from file[0] -> blob.slice -> filereader.asArrayBuffer -> Uint8Array
array = [37, 80, 68, 70, 45, 49, 46, 51, 13, 10, 37, 226, 227, 207, 211, 13, 10, 13, 10, 49, 32, 48, 32, 111, ...]
How could I do the reverse engineer? Create a new File Object from the above array?
I'm creating a file object through
bytes = [37, 80, 68, 70, 45, 49, 46, 51, 13, 10, 37, 226, 227, 207, 211, 13, 10, 13, 10, 49, 32, 48, 32, 111, 98, 106, 13, 10, 60, 60, 13, 10, 47, 84, 121, 112, 101, 32, 47, 67, 97, 116, 97, 108, 111, 103, 13, 10, 47, 79, 117, 116, 108, 105, 110, 101, 115, 32, 50, 32, 48, 32, 82, 13, 10, 47, 80, 97, 103, 101, 115, 32, 51, 32, 48, 32, 82, 13, 10, 62, 62, 13, 10, 101, 110, 100, 111, 98, 106, 13, 10, 13, 10, 50, 32, 48, 32, 111, 98, 106]
let testFile = new File([bytes],"application/pdf")
let testFile = new File(bytes,"application/pdf")
Is my code making sense? If not, how do I convert those bytes into a correct one?
content = Uint8Array.from([37, ... 106])
file = new File([content])
reader.readAsArrayBuffer(file);
reader.onload = function (e) {
const fileType = doTask(e.target.result);
}
function doTask(arrBuffer) {
const byteArray = [];
for (let i = 0; i < 4; i++) {
byteArray.push(arrayBuffer[i]);
}
let headerContent = '';
// Create the headerContent
for (let i = 0; i < byteArray.length; i++) {
headerContent += byteArray[i].toString(16);
}
// Uncaught TypeError: Cannot read property 'toString' of undefined
}
Upvotes: 1
Views: 5174
Reputation: 1003
I believe I resolved this. In my situation, I have a Google App Script project I'm working on and the DriveApp Blob class has a .getBytes() function.
What you need to do is take that Byte[] and convert it to an unsigned 8 bit array and pass that to the File constructor. Be sure to also include the second required argument of filename as well.
One example from App Script
var file = DriveApp.getFileById(fileId);
var bytes = file.getBlob().getBytes();
new File([new Uint8Array(bytes)], 'filename', {type: 'mimeType'})
So for anyone else, simply get your byte array data in a variable called bytes. Type is optional, but useful.
new File([new Uint8Array(bytes)], 'filename', {type: 'mimeType'})
Upvotes: 2