How to Read a File (DOCX or XLSX OR PNG) as Binary stream in Internet Explorer using JavaScript

1.1k views Asked by At

For one of our customer, we are required to use HTML File Input control, to upload the file to another server using REST Web Services. I was able to achieve this using HTML FileReader.readAsArrayBuffer Method. But since users are using IE8 and IE9, HTML5 APIs are not supported. I tried using below code, but this reads only TXT file not other file types like DOCX or PNG

reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
2

There are 2 answers

0
Pierre On

I use file inputs in a weird working way in IE8, maybe it can help you:

var form = document.createElement("form");
form.method = 'POST';
form.action = url;
form.target = '_blank';
form.encoding = form.enctype = "multipart/form-data";
form.appendChild(fileInput);

document.body.appendChild(form);
form.submit();

It sends the file chosen via fileInput as a POST request to the server, without reading its binary content. Do you absolutely need to read the file client-side ?

If you need cross-site upload, I think there are some iframe hacks for IE working.

0
user3099482 On

Thank You for your quick response. The Web service which I am using is RESTfull service and accept the file as Base64string. So I need to read the file content at client side itself, convert it as Base64 String and pass it to the WebService. So I cannot use Post in there.

This is fully-being a client-side dependent script and at same time there is no handle at server side component I tried options of using ActiveX, but due to some security reason, we cannot proceed with that. I also tried ADO.Stream but even that uses ActiveX.

Thanks, Aravind