Using JavaScript to read binary files and use ajax to transmit binary streams, javascriptajax
Based on Multiple tutorials on the Internet and the methods obtained by our own practices, Alibaba Cloud is currently compatible with Google, IE11, and ie10.
There is nothing special about htmlbody content.
<Div id = "dConfirm"> <p style = "float: left; margin-left: 20px; margin-top: 20px"> <form action = "javascript: uploadAndSubmit (); "name =" demoForm "id =" demoForm "method =" post "enctype =" multipart/form-data "> <p> upload files: <input type = "file" name = "file" id = "str_file"/> </p> <input type = "submit" value = "Upload"/> </p> </form> </p> </div>
Read Binary files:
Function uploadAndSubmit () {filename = document. getElementById ("str_file"). value; var form = document. forms ["demoForm"]; if (filename! = "") {Try {var obj = new ActiveXObject ("ADODB. stream "); // This Must Be IE} catch (e) {var file = form [" file "]. files [0]; var reader = new FileReader (); reader. readAsBinaryString (file); // The reader Method is asynchronous. onloadend = function () {// This event triggers if (reader. error) {console. log (reader. error);} else {uploadAndSubmit2 (reader. result) ;}} return;} var bf1 = new BinaryFile (filename); // The read method is synchronous uploadAndSubmit2 (bf1.ReadAll ());}}
Here we need to make a judgment on the browser type. If it is not IE, FileReader will be used for reading, and if it is IE, activex control will be used for reading. There is a pitfall here. Although IE11 and IE10 do not support the FileReader object method, the "typeof FileReader" of IE11 and IE10 is not "undefined ", it is difficult to distinguish browsers directly by whether FileReader is supported. It should also be noted that the FileReader method is asynchronous file reading and activex is synchronous file reading. I have never thought about how these two routes are encapsulated in one method. I wonder if you have any good solutions.
Here, the constructor of BinaryFile object is from http://www.codeproject.com/Articles/17825/Reading-and-Writing-Binary-Files-Using-JScript? Msg = 3718403 # xx3718403xx technical blog, there is an improvement method in the blog's reply that is said to be more efficient, but because I did not understand it, I chose the original method.
The original method is long:
// Use ADODB. the conversion function BinaryFile (name) between the ISO-8859-1 and the Windows-1252 Character Set when using the Stream Control) {var adTypeBinary = 1var adTypeText = 2var adSaveCreateOverWrite = 2 // The trick-this is the 'old fassioned' not translation page // It lest javascript use strings to act like raw octetsvar codePage = '123 '; this. path = name; var forward = new Array (); var backward = new Array (); // Note-for better performance I shocould preconv Ert these hex // definitions to decimal-at some point :-)-AJTforward ['80'] = '00c7 '; forward ['81'] = '00fc '; forward ['82 '] = '00e9'; forward ['83'] = '00e2'; forward ['84 '] = '00e4 '; forward ['85'] = '00e0'; forward ['86'] = '00e5'; forward ['87 '] = '00e7 '; forward ['88 '] = '00ea'; forward ['89 '] = '00eb'; forward ['8a '] = '00e8 '; forward ['8b '] = '00ef'; forward ['8c'] = '00ee '; forward ['8d'] = '00ec '; forward ['8e'] = '00c4'; forward ['8f'] = '00c5 '; forward ['90'] = '00c9'; forward ['91 '] = '00e6 '; forward ['92 '] = '00c6'; forward ['93 '] = '00f4'; forward ['94 '] = '00f6 '; forward ['95'] = '00f2'; forward ['96 '] = '00fb'; forward ['97 '] = '00f9 '; forward ['98 '] = '00ff'; forward ['99'] = '00d6'; forward ['9a '] = '00dc '; forward ['9b'] = '00a2 '; forward ['9c'] = '00a3'; forward ['9d'] = '00a5 '; forward ['9e'] = '20a7 '; forward ['9f'] = '123 '; Forward ['a0 '] = '00e1'; forward ['a1'] = '00ed'; forward ['a2 '] = '00f3 '; forward ['a3 '] = '00fa'; forward ['a4 '] = '00f1'; forward ['a5 '] = '00d1 '; forward ['a6 '] = '00a'; forward ['a7'] = '00ba'; forward ['a8 '] = '00bf '; forward ['a9 '] = '000000'; forward ['a'] = '00ac'; forward [' AB '] = '00bd '; forward ['ac'] = '00bc'; forward ['ad'] = '00a1'; forward ['AE'] = '00ab '; forward ['af'] = '00bb '; forward ['b0'] = '000000'; forward [' B1 '] = '000000'; forward ['b2'] = '000000'; forward ['b3'] = '000000 '; forward ['b4 '] = '000000'; forward ['b5'] = '000000'; forward ['b6 '] = '000000 '; forward ['b7 '] = '000000'; forward ['b8'] = '000000'; forward ['b9'] = '000000 '; forward ['ba'] = '000000'; forward ['bb'] = '000000'; forward ['bc'] = '255d '; forward ['bd '] = '255c'; forward ['be'] = '255b '; forward ['bf'] = '123 '; forward ['c0 '] = '000000'; forward ['c1'] = '000000'; forward ['c2'] = '2 52C '; forward ['c3'] = '251c'; forward ['c4 '] = '000000'; forward ['c5'] = '253c '; forward ['c6 '] = '255e'; forward ['c7'] = '255f'; forward ['c8 '] = '255a '; forward ['c9 '] = '000000'; forward ['CA'] = '000000'; forward ['cb'] = '000000 '; forward ['cc'] = '20160301'; forward ['cd'] = '20160301'; forward ['ce '] = '256c '; forward ['cf '] = '000000'; forward ['d0'] = '000000'; forward ['d1'] = '000000 '; forward ['d2 '] = '123'; forward ['d3'] = '123'; forw Ard ['d4 '] = '123'; forward ['d5'] = '123'; forward ['d6 '] = '123 '; forward ['d7'] = '256b '; forward ['d8'] = '256a'; forward ['d9'] = '123 '; forward ['da'] = '250c'; forward ['db'] = '000000'; forward ['dc'] = '000000 '; forward ['dd'] = '258c'; forward ['de'] = '000000'; forward ['df'] = '000000 '; forward ['e0'] = '03b1 '; forward ['e1'] = '00df '; forward ['E2'] = '123 '; forward ['e3 '] = '03c0'; forward ['e4 '] = '03a3'; forward ['e5'] = '03c3'; forward ['e6 '] = '00b5'; forward ['e7 '] = '03c1'; forward ['e8'] = '03a6 '; forward ['e9'] = '000000'; forward ['ea '] = '03a9'; forward ['EB '] = '03b4 '; forward ['EC'] = '221e '; forward ['ed'] = '03c6'; forward ['ee '] = '03b5 '; forward ['ef '] = '000000'; forward ['f0'] = '000000'; forward ['f1'] = '00b1 '; forward ['F2'] = '20160301'; forward ['f3 '] = '20160301'; forward ['f1'] = '20160301 '; forward ['f5'] = '20140901'; forward ['f6 '] = '00f7'; Forward ['f7 '] = '000000'; forward ['f8'] = '00b0'; forward ['f9'] = '000000 '; forward ['fa '] = '00b7'; forward ['fb '] = '221a'; forward ['fc '] = '207f '; forward ['fd '] = '00b2'; forward ['fe'] = '25a0 '; forward ['ff'] = '00a0 '; backward ['c7'] = '80'; backward ['fc '] = '81'; backward ['e9'] = '82 '; backward ['E2'] = '83 '; backward ['e4'] = '84 '; backward ['e0'] = '85 '; backward ['e5'] = '86'; backward ['e7 '] = '87'; backward ['ea '] = '88 '; backward ['EB'] = '89 '; backward ['e8'] = '8a'; backward ['ef '] = '8b '; backward ['ee '] = '8c'; backward ['EC'] = '8d'; backward ['c1'] = '8e '; backward ['c5 '] = '8f'; backward ['c9'] = '90'; backward ['e6 '] = '91 '; backward ['c6 '] = '92'; backward ['f4'] = '93 '; backward ['f6'] = '94 '; backward ['F2'] = '95'; backward ['fb '] = '96'; backward ['f9'] = '97 '; backward ['ff '] = '98'; backward ['d6 '] = '99'; backward ['DC'] = '9a '; Backward ['a2'] = '9b'; backward ['a3 '] = '9c'; backward ['a5'] = '9d '; backward ['20a7 '] = '9e'; backward ['000000'] = '9f'; backward ['e1'] = 'a0 '; backward ['ed'] = 'a1'; backward ['f3 '] = 'a2'; backward ['fa '] = 'a3 '; backward ['f1 '] = 'a4'; backward ['d1 '] = 'a5'; backward ['a'] = 'a6 '; backward ['ba'] = 'a7 '; backward ['bf'] = 'a8'; backward ['000000'] = 'a9 '; backward ['ac'] = 'a'; backward ['bd '] =' AB '; backward ['bc'] = 'a C '; backward ['a1'] = 'ad'; backward [' AB '] =' AE '; backward ['bb'] = 'af '; backward ['000000'] = 'b0'; backward ['000000'] = 'b1 '; backward ['000000'] = 'b2 '; backward ['000000'] = 'b3'; backward ['000000'] = 'b4 '; backward ['000000'] = 'b5 '; backward ['000000'] = 'b6 '; backward ['000000'] = 'b7'; backward ['000000'] = 'b8 '; backward ['000000'] = 'b9'; backward ['000000'] = 'ba'; backward ['000000'] = 'bb '; backward ['255d '] = 'bc'; backward ['255c'] = 'Bd '; backward ['255b'] = 'be'; backward ['000000'] = 'bf'; backward ['000000'] = 'c0 '; backward ['000000'] = 'c1'; backward ['252c '] = 'c2'; backward ['251c '] = 'c3 '; backward ['000000'] = 'c4 '; backward ['253c'] = 'c5 '; backward ['255e'] = 'c6 '; backward ['255f'] = 'c7'; backward ['255a '] = 'c8'; backward ['123'] = 'c9 '; backward ['000000'] = 'CA'; backward ['000000'] = 'cb '; backward ['000000'] = 'cc '; backward ['000000'] = 'cd'; backward ['2 56C '] = 'ce'; backward ['000000'] = 'cf '; backward ['000000'] = 'd0 '; backward ['123'] = 'd1 '; backward ['123'] = 'd2'; backward ['123'] = 'd3 '; backward ['000000'] = 'd4 '; backward ['000000'] = 'd5'; backward ['000000'] = 'd6 '; backward ['256b '] = 'd7'; backward ['256a'] = 'd8'; backward ['123'] = 'd9 '; backward ['250c'] = 'da'; backward ['000000'] = 'db'; backward ['000000'] = 'dc '; backward ['258c'] = 'dd'; backward ['000000'] = 'de'; bac Kward ['000000'] = 'df '; backward ['3b1'] = 'e0'; backward ['df '] = 'e1 '; backward ['000000'] = 'E2'; backward ['3c0 '] = 'e3'; backward ['3a3 '] = 'e4 '; backward ['3c3'] = 'e5'; backward ['b5 '] = 'e6'; backward ['3c4 '] = 'e7 '; backward ['3a6 '] = 'e8'; backward ['000000'] = 'e9'; backward ['3a9'] = 'ea '; backward ['3b4 '] = 'EB'; backward ['221e '] = 'EC'; backward ['3c6'] = 'ed '; backward ['3b5 '] = 'ee'; backward ['000000'] = 'ef '; backward ['2 261 '] = 'f0'; backward ['b1 '] = 'f1'; backward ['000000'] = 'F2 '; backward ['000000'] = 'F3'; backward ['000000'] = 'F4'; backward ['000000'] = 'f5 '; backward ['f7 '] = 'f6'; backward ['000000'] = 'f7 '; backward ['b0'] = 'f8 '; backward ['000000'] = 'f9'; backward ['b7 '] = 'fa'; backward ['221a '] = 'fb '; backward ['207f'] = 'fc'; backward ['b2'] = 'fs'; backward ['25a0 '] = 'fe '; backward ['a0 '] = 'ff'; var hD = "0123456789 ABCDEF"; this. d2h = fu Nction (d) {var h = hD. substr (d & 15,1); while (d> 15) {d> = 4; h = hD. substr (d & 15,1) + h;} return h;} this. h2d = function (h) {return parseInt (h, 16);} this. writeAll = function (what) {// Create Stream object // var BinaryStream = WScript. createObject ("ADODB. stream "); var BinaryStream = new ActiveXObject (" ADODB. stream "); // Specify stream type-we cheat and get string but 'like' binaryBinaryStream. type = adTypeText; Binary Stream. charSet = '000000'; // Open the streamBinaryStream. open (); // Write to the streamBinaryStream. writeText (this. forward437 (what); // Write the string to the diskBinaryStream. saveToFile (this. path, adSaveCreateOverWrite); // Clearn upBinaryStream. close ();} this. readAll = function () {// Create Stream object-needs ADO 2.5 or heigher // var BinaryStream = WScript. createObject ("ADODB. stream ") var BinaryStream = New ActiveXObject ("ADODB. stream "); // Specify stream type-we cheat and get string but 'like' binaryBinaryStream. type = adTypeText; BinaryStream. charSet = codePage; // Open the streamBinaryStream. open (); // Load the file data from disk To stream objectBinaryStream. loadFromFile (this. path); // Open the stream And get binary 'string' from the objectvar what = BinaryStream. readText; // Clean upBinaryStream. C Lose (); return this. backward437 (what);}/* Convert a octet number to a code page 437 char code */this. forward437 = function (inString) {var encArray = new Array (); var tmp = ''; var I = 0; var c = 0; var l = inString. length; var cc; var h; for (; I <l ;++ I) {c ++; if (c = 128) {encArray. push (tmp); tmp = ''; c = 0;} cc = inString. charCodeAt (I); if (cc <128) {tmp + = String. fromCharCode (cc);} else {h = this. d2h (cc); h = forward [''+ h]; tmp + = String. from CharCode (this. h2d (h) ;}} if (tmp! = '') {EncArray. push (tmp);} // this loop progressive concatonates the // array elements entil there is only onevar ar2 = new Array (); for (; encArray. length> 1;) {var l = encArray. length; for (var c = 0; c <l; c + = 2) {if (c + 1 = l) {ar2.push (encArray [c]);} else {ar2.push (''+ encArray [c] + encArray [c + 1]) ;}} encArray = ar2; ar2 = new Array ();} return encArray [0];}/* Convert a code page 437 char code to a octet number */this. backward437 = Function (inString) {var encArray = new Array (); var tmp = ''; var I = 0; var c = 0; var l = inString. length; var cc; var h; for (; I <l ;++ I) {c ++; if (c = 128) {encArray. push (tmp); tmp = ''; c = 0;} cc = inString. charCodeAt (I); if (cc <128) {tmp + = String. fromCharCode (cc);} else {h = this. d2h (cc); h = backward [''+ h]; tmp + = String. fromCharCode (this. h2d (h) ;}} if (tmp! = '') {EncArray. push (tmp);} // this loop progressive concatonates the // array elements entil there is only onevar ar2 = new Array (); for (; encArray. length> 1;) {var l = encArray. length; for (var c = 0; c <l; c + = 2) {if (c + 1 = l) {ar2.push (encArray [c]);} else {ar2.push (''+ encArray [c] + encArray [c + 1]) ;}} encArray = ar2; ar2 = new Array ();} return encArray [0] ;}}
The main part is:
this.ReadAll = function(){//Create Stream object - needs ADO 2.5 or heigher//var BinaryStream = WScript.CreateObject("ADODB.Stream")var BinaryStream = new ActiveXObject("ADODB.Stream");//Specify stream type - we cheat and get string but 'like' binaryBinaryStream.Type = adTypeText;BinaryStream.CharSet = codePage;//Open the streamBinaryStream.Open();//Load the file data from disk To stream objectBinaryStream.LoadFromFile(this.path);//Open the stream And get binary 'string' from the objectvar what = BinaryStream.ReadText;// Clean upBinaryStream.Close();return this.Backward437(what);}
Here is the method for reading files using the "ADODB. Stream" control. We can see that the read type used by the author is adTypeText (2), and the binary file is read using text! However, after the document is changed to the adTypeBinary (1) type, NO content is read and I don't know why.
The rest of the code is in the encoding conversion work, the general meaning is to read the file to use the "ISO-8859-1" character set, with http to send the file to use the "Windows-1252" character set, these two character sets have only a small number of characters, so we can find the different parts in the data to be converted to another character set.
Ajax sends a binary stream:
Function uploadAndSubmit2 (BinaryContent) {Url = UrlHead + "Cook. ashx"; xmlHttp = new XMLHttpRequest (); xmlHttp. open ("POST", Url + "? Method = post & func = file_upload & fileName = "+ encodeURIComponent (filename. split ("\") [filename. split ("\\"). length-1]); // IE processes Chinese characters urlxmlHttp. sendAsBinary (BinaryContent); xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4) {if (xmlHttp. status = 200) {var str = xmlHttp. response; alert (str); xmlHttp. abort ();}}}}
In order to perform binary transmission, the "window. activeXObject ("Msxm12.XMLHTTP") "and" window. activeXObject ("Microsoft. XMLHTTP ")", I wonder if you have supported the binary transmission methods of the two activex controls.
In a tutorial, there is a line before Row 6:
XmlHttp. overrideMimeType ('text \/plain; charset = x-user-defined'); //: x-user-defined tells the browser not to parse the returned data
After this line is added, the browser will not parse the encoding format of the data returned from the background. Specifically, the Chinese text returned to the foreground is displayed as "" or "Port ", I guess the author is doing this to receive binary data from the background at the front end.
In fact, only Firefox's XMLHttpRequest supports the sendAsBinary method. To use it in IE and Google, you need to add a prototype method for XMLHttpRequest:
// Add the binary sending function XMLHttpRequest to the XMLHttpRequest prototype. prototype. sendAsBinary = function (datastr) {function byteValue (x) {return x. charCodeAt (0) & 0xff;} var ords = Array. prototype. map. call (datastr, byteValue); var ui8a = new Uint8Array (ords); this. send (ui8a. buffer );}
The code here is not quite understandable, and the sixth line of IE8 is not supported, and the seventh line of IE9 is not supported.
Java serverlet is used in the background, and the code of the final called java class is as follows:
Public String FileUpload (HttpServletRequest request) throws IOException {request. setCharacterEncoding ("UTF-8"); BufferedInputStream fileIn = new BufferedInputStream (request. getInputStream (); String fn = request. getParameter ("fileName"); byte [] buf = new byte [1024]; File file = new File ("d:/" + fn ); bufferedOutputStream fileOut = new BufferedOutputStream (new FileOutputStream (file); try {while (true) {// read data int bytesIn = fileIn. read (buf, 0, 1024); System. out. println (bytesIn); if (bytesIn =-1) {break;} else {fileOut. write (buf, 0, bytesIn) ;}} fileOut. flush (); return ("saved successfully");} catch (Exception e) {return "failed to save because:" + e. toString ();} finally {fileOut. close ();}}
The above section describes how to use JavaScript to read binary files and use ajax to transmit binary streams. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!