I have the byte array in javascript. How convert this array to file for upload?
Asked
Active
Viewed 6,237 times
1
-
Is this what you are after? http://stackoverflow.com/questions/12603307/convert-byte-array-to-the-original-file-in-javascript – Tobias Nilsson Jan 09 '13 at 09:12
-
For upload? Why would you want to convert anything? Just send it via AJAX and do whatever you want with it on the server side. – freakish Jan 09 '13 at 09:16
-
Some more details about what you want will help. – Pulkit Goyal Jan 09 '13 at 09:27
-
There is HTML5 solution https://stackoverflow.com/q/23451726/2587343 – Vlastimil Ovčáčík Jun 18 '17 at 18:11
2 Answers
1
you create a file like this
new File([you byte here], 'name of your file', { type: 'you extention', lastModified: new Date() });
if the your byte is string
new File([this.base64ToArrayBuffer(you string)], 'file name', { type: this.handleFileDataType(DocExtension), lastModified: new Date() });
base64ToArrayBuffer = (base64) => {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
handleFileDataType = ext => {
switch (ext) {
case 'pdf':
return 'application/pdf';
case 'jpg':
return 'image/jpeg';
case 'jpeg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'tiff':
return 'image/tiff';
case 'docx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
}
};

Ait Friha Zaid
- 1,222
- 1
- 13
- 20
0
What I got from your question is that you have a Byte Array and you want to write these Byte Array to a file and upload it to server.
No, It is not possible in JavaScript because JavaScript doesn't have access to writing files as this would be a huge security risk.

Heretic Monkey
- 11,687
- 7
- 53
- 122

Pranav
- 8,563
- 4
- 26
- 42