PC8 / CP437 character set with filereader in Chrome - javascript
anyone knows if it is possible to get the FileReader API in chrome to read a file with the CP437 character set? Is there a place where I can list the available encodings?
Currently, my workaround is to read it with CP1251 reader.readAsText(file, 'CP1251') and manually replace special characters, which is not cool!
Is there other browsers which support this character set? Or do you have any better idea at a workaround?
Edit: The file is parsed only in the browser, there is no backend available.
regards Oskar
I had the same problem. CP437 isn't implemented (in Chrome and Firefox at least).
Work around to convert to UTF-8 that requires ArrayBuffer support in the browser:
var Cp437Helper = function () {
var cp437map = [
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006',
'\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D',
'\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014',
'\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001A', '\u001B',
'\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022',
'\u0023', '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F', '\u0030',
'\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037',
'\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E',
'\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045',
'\u0046', '\u0047', '\u0048', '\u0049', '\u004A', '\u004B', '\u004C',
'\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A',
'\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0060', '\u0061',
'\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068',
'\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F',
'\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076',
'\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u007F', '\u00C7', '\u00FC', '\u00E9', '\u00E2', '\u00E4',
'\u00E0', '\u00E5', '\u00E7', '\u00EA', '\u00EB', '\u00E8', '\u00EF',
'\u00EE', '\u00EC', '\u00C4', '\u00C5', '\u00C9', '\u00E6', '\u00C6',
'\u00F4', '\u00F6', '\u00F2', '\u00FB', '\u00F9', '\u00FF', '\u00D6',
'\u00DC', '\u00A2', '\u00A3', '\u00A5', '\u20A7', '\u0192', '\u00E1',
'\u00ED', '\u00F3', '\u00FA', '\u00F1', '\u00D1', '\u00AA', '\u00BA',
'\u00BF', '\u2310', '\u00AC', '\u00BD', '\u00BC', '\u00A1', '\u00AB',
'\u00BB', '\u2591', '\u2592', '\u2593', '\u2502', '\u2524', '\u2561',
'\u2562', '\u2556', '\u2555', '\u2563', '\u2551', '\u2557', '\u255D',
'\u255C', '\u255B', '\u2510', '\u2514', '\u2534', '\u252C', '\u251C',
'\u2500', '\u253C', '\u255E', '\u255F', '\u255A', '\u2554', '\u2569',
'\u2566', '\u2560', '\u2550', '\u256C', '\u2567', '\u2568', '\u2564',
'\u2565', '\u2559', '\u2558', '\u2552', '\u2553', '\u256B', '\u256A',
'\u2518', '\u250C', '\u2588', '\u2584', '\u258C', '\u2590', '\u2580',
'\u03B1', '\u00DF', '\u0393', '\u03C0', '\u03A3', '\u03C3', '\u00B5',
'\u03C4', '\u03A6', '\u0398', '\u03A9', '\u03B4', '\u221E', '\u03C6',
'\u03B5', '\u2229', '\u2261', '\u00B1', '\u2265', '\u2264', '\u2320',
'\u2321', '\u00F7', '\u2248', '\u00B0', '\u2219', '\u00B7', '\u221A',
'\u207F', '\u00B2', '\u25A0', '\u00A0'
];
this.convertToUTF8 = function (buffer) {
var out = '';
var view = new DataView(buffer);
var i ;
var n = view.byteLength;
for (i = 0; i < n; i ++) {
var uint = view.getUint8(i);
if (cp437map[ uint ] == undefined) {
out += '/' + uint + '/';
} else {
out += cp437map[ uint ];
}
}
return out;
};
if ( Cp437Helper.prototype._instance == undefined ) {
Cp437Helper.prototype._instance = this;
}
return Cp437Helper.prototype._instance;
};
Use the above:
var getTextFromCP437File = function ( file ) {
var reader = new FileReader();
reader.onload = function(e) {
var text = Cp437Helper().convertToUTF8(reader.result);
// do something...
};
//reader.readAsText(file, 'cp437');
reader.readAsArrayBuffer(file);
};
Related
Is there a way of solving activee x error
I have a below piece of code which is working only with IE because of active X parser and I need to run it in chrome and other latest browsers. < script language = "jscript" type = "text/javascript" > function Transform1() { var xml1 = new ActiveXObject("Microsoft.XMLDOM"); xml1.async = false; xml1.load(frmSoap.TestXml.value); frmSoap.Body.value = xml1.xml; } < /script> I tried to fix it by using the below change but it did not work for me and instead stopped working in ie as well. function Transform1() if (window.DOMParser) { var parser, xml1; parser = new DOMParser(); xml1 = parser.parseFromString(frmSoap.TestXml.value,"text/xml"); frmSoap.Body.value = xml1.xml; } else { var xml1 = new ActiveXObject("Microsoft.>XMLDOM"); xml1.async = false; xml1.load(frmSoap.TestXml.value); frmSoap.Body.value = xml1.xml; } Can somebody help me fix this issue.
Here is an approach that will work for you in all browsers. This is through the use of createDocument() and then having the browser parse the XML for you. Please refer to the comments in the code. //Mock const frmSoap = { TestXml: { value: `<productListing title="ABC Products"> <product> <name>Product One</name> <description>Product One is an exciting new widget that will simplify your life.</description> <cost>$19.95</cost> <shipping>$2.95</shipping> </product> </productListing>` } } // Create an XHTML document var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'xhtml', null); // Add body var body = document.createElementNS('http://www.w3.org/1999/xhtml', 'body'); doc.documentElement.appendChild(body); // Parse the XML document and place it in the new XML doc body body.innerHTML = frmSoap.TestXml.value; //Parse the XML to produce output const title = body.querySelector('productListing').getAttribute('title'); const productName = body.querySelector("product name").textContent; const productDescription = body.querySelector("product description").textContent; //Use the XML data document.getElementById("output").innerHTML = `<h1>${title}</h1><span>Product Name:</span> ${productName}, <br><span>Product Description:</span> ${productDescription}`; // Remove the doc when no longer needed doc = null; span { font-weight: bold; } <div id="output"></div>
Upload Multiple Image using multiple file control in asp.net mvc 4.0 (angular js)
I am using Visual Studio 2012 Express with Framework 4.5 MVC. I am also using Angular Js for the first time. I have a view page that contains the multiple browse (file) button that will be use for upload single image by selecting each of them individually with my form data. The problem is that by using submit button I am not able to get the images but I got the form data. I want to get the images with the form data using Angular js. I have already referred below posts but not getting the solution: LINK 1 LINK 2 Please anyone help me to solve out this problem, would be appreciated.
I have a sample code for the uploading of multiple image using angularjs. This link might help you: https://jsfiddle.net/n9tL7cdr/1/ <div ng-app="test"> <div ng-controller="UploadCtrl"> <table> <tr ng-repeat="i in [1, 2, 3, 4]"> <td>{{i}}</td> <td> <input type="file" name="file" onchange="angular.element(this).scope().photoChanged(this.files)" /> </td> <td> <img ng-src="{{ image[$index].dataUrl }}" height="50px" /> </td> </tr> </table> </div> CONTROLLER: angular.module('test', []); angular.module('test').controller('UploadCtrl', function ($scope, $timeout) { // Variable for image. $scope.image = { dataUrl: [] }; $scope.fileReaderSupported = window.FileReader != null; $scope.photoChanged = function (files, index) { if (files != null) { var file = files[0]; var index = this.$index; // index of image. if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) { $timeout(function () { var fileReader = new FileReader(); fileReader.readAsDataURL(file); fileReader.onload = function (e) { $timeout(function () { $scope.image[index] = {dataUrl: e.target.result}; // Retrieve the image. }); } }); } } }; });
Here i find the solution using HttpPostedFileBase and Form Collection. public ActionResult AddImageUpload(IEnumerable<HttpPostedFileBase> files,FormCollection fc ) { ImageUpload IU = new ImageUpload(); IU.MaterialId = Convert.ToInt32((fc["MaterialId"]).Replace("number:","")); IU.CategoryId = Convert.ToInt32((fc["CategoryId"]).Replace("number:", "")); string tr = fc["hdnSub"].ToString(); string result = null; string Message, fileName, actualFileName; Message = fileName = actualFileName = string.Empty; bool flag = false; //HttpPostedFileBase f= IU.ImageP; string[] SubAssemblyId = (tr.Split(',')); int i = 0; string databaseid = null; for (int j=0 ; j<files.Count(); j++) { var fileContent = Request.Files[j]; if (fileContent.FileName != "") { databaseid = SubAssemblyId[i]; string fn = DateTime.Now.ToShortDateString().Replace("/", "") + DateTime.Now.TimeOfDay.Hours + DateTime.Now.TimeOfDay.Minutes + DateTime.Now.TimeOfDay.Seconds + DateTime.Now.TimeOfDay.Milliseconds + Path.GetExtension(fileContent.FileName); fileName = fn; try { if (fileContent != null && fileContent.ContentLength > 0) { var inputStream = fileContent.InputStream; var path = Path.Combine(Server.MapPath("/Images/Product/"), fn); using (var fileStream = System.IO.File.Create(path)) { inputStream.CopyTo(fileStream); } } } catch (Exception) { } } i++; } return RedirectToAction("ImageUpload"); }
HTML-Only Website w/ Theme Options
I am creating a html-only(no server sided code) website that supposed to have multiple themes, Wherein user can select/change a theme to view the website. Can you suggest some concepts on how to do this or at least point me into some helpful articles. Thank you for your help in advance.
The most common approach is to use different external CSS stylesheets, that will get switched based on the selected theme. You also need to structure your DOM wisely, so as to allow different layouts provided by themes.
Probably overkill... but here is a font selector example I came up with using Google Font API and a Document Fragment Builder script I wrote a while ago. var FragBuilder = (function() { var applyStyles = function(element, style_object) { for (var prop in style_object) { element.style[prop] = style_object[prop]; } }; var generateFragmentFromJSON = function(json) { var tree = document.createDocumentFragment(); json.forEach(function(obj) { if (!('tagName' in obj) && 'textContent' in obj) { tree.appendChild(document.createTextNode(obj['textContent'])); } else if ('tagName' in obj) { var el = document.createElement(obj.tagName); delete obj.tagName; for (part in obj) { var val = obj[part]; switch (part) { case ('textContent'): el.appendChild(document.createTextNode(val)); break; case ('style'): applyStyles(el, val); break; case ('childNodes'): el.appendChild(generateFragmentFromJSON(val)); break; default: if (part in el) { el[part] = val; } break; } } tree.appendChild(el); } else { throw "Error: Malformed JSON Fragment"; } }); return tree; }; var generateFragmentFromString = function(HTMLstring) { var div = document.createElement("div"), tree = document.createDocumentFragment(); div.innerHTML = HTMLstring; while (div.hasChildNodes()) { tree.appendChild(div.firstChild); } return tree; }; return function(fragment) { if (typeof fragment === 'string') { return generateFragmentFromString(fragment); } else { return generateFragmentFromJSON(fragment); } }; }()); function jsonp(url) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; document.getElementsByTagName('body')[0].appendChild(script); } function replacestyle(url) { if (!document.getElementById('style_tag')) { var style_tag = document.createElement('link'); style_tag.rel = 'stylesheet'; style_tag.id = 'style_tag'; style_tag.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(style_tag); replacestyle(url); } document.getElementById('style_tag').href = url; } function loadFonts(json) { var select_frag = [ { 'tagName': 'select', 'id': 'font-selection', 'childNodes': [ { 'tagName': 'option', 'value': 'default', 'textContent': 'Default'} ]} ]; json['items'].forEach(function(item) { var family_name = item.family, value = family_name.replace(/ /g, '+'); if (item.variants.length > 0) { item.variants.forEach(function(variant) { value += ':' + variant; }); } select_frag[0].childNodes.push({ 'tagName': 'option', 'value': value, 'textContent': family_name }); }); document.getElementById('container').appendChild(FragBuilder(select_frag)); document.getElementById('font-selection').onchange = function(e) { var font = this.options[this.selectedIndex].value, name = this.options[this.selectedIndex].textContent; if (font === 'default') { document.getElementById('sink').style.fontFamily = 'inherit'; } else { document.getElementById('sink').style.fontFamily = name; replacestyle('https://fonts.googleapis.com/css?family=' + font); } }; } jsonp("https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyDBzzPRqWl2eU_pBMDr_8mo1TbJgDkgst4&sort=trending&callback=loadFonts"); Here is the Kitchen Sink example...
You could use jQuery style switchers. Check out below link which also have step-by-step tutorials on how to do it: http://www.net-kit.com/10-practical-jquery-style-switchers/ There is also an article of how to do it here: http://net.tutsplus.com/tutorials/javascript-ajax/jquery-style-switcher/
Cudos answered already to this question but I'll post this anyway. You can modify this tutorial (http://net.tutsplus.com/tutorials/javascript-ajax/jquery-style-switcher/) posted by Cudos to consist only of client side code with these modifications to index.php file. Remove the PHP block and add this function. <script language="javascript" type="text/javascript"> function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } var js_style = readCookie(style); </script> And replace the PHP style switcher with this. <script language="javascript" type="text/javascript"> if (typeof js_style == 'undefined') { js_style = 'day'; } document.write('<link id="stylesheet" type="text/css" href="css/' + js_style + '.css" rel="stylesheet" />'); </script> Worked for me...
As Alexander Pavlov writes in his answer, use different external style sheets. To make it possible to users to select a theme persistently (i.e., so that the theme is preserved when moving to another page of the site, or when returning to the site next day), use either HTTP cookies or HTML5-style localStorage. They let you store information locally in the user’s computer, without any server-side code. There are many tutorials on localStorage (also known as HTML storage or Web storage), and it’s difficult to pick up any particular. They are more flexible than cookies, and they could be used to store large amounts of data, even user-tailored stylesheets. The main problem with localStorage is lack of support on IE 7 and earlier. You might decide that people using them just won’t get the customizability. Alternatively, you can use cookiers, userData (IE), dojox.storage, or other tools to simulate localStorage on antique browsers.
Explanation of this JavaScript Code
I'm not too good on the whole JavaScript (I can do some basic validations) but this isn't my zone I've got a piece of code below that I'm trying to understand what it does, I can read any code and understand a few parts, but this just stumped me. Here: function tm_search_click() { if (document.getElementById('tm').value == 'Enter your trademark') { document.getElementById('tm').style.backgroundColor = '#fcc'; return false; } else { window.location = '?tm=' + escape(document.getElementById('tm').value); return true; } } function qs(a) { a = a.replace(/[[]/, "\[").replace(/[]]/, "\]"); var b = "[\?&]" + a + "=([^&#]*)"; var c = new RegExp(b); var d = c.exec(window.location.href); return d == null ? "" : decodeURIComponent(d[1]).replace(/+/g, " ") } if (qs("tm") != "") { tm_trademark = document.getElementById("tm").value = unescape(qs("tm")); tm_partner = "migu2008"; tm_frame_width = 630; tm_frame_height = "auto"; tm_trademark_country_code = "GB"; tm_css_url = "http://remarqueble.com/api/theme/search_corporate.css"; document.getElementById("tmLoading").style.display = "block"; tm_on_search_result = function () { document.getElementById("tmLoading").style.display = "none"; document.getElementById("tmLoaded").style.display = "block" } } else { tm_search_method = "none" } That is all of it without the <script> tags. Could I also edit this code so that it searches are made based on what option the user inputs?
I think it works like this (assuming that this is in tags inside html page) Page loads. The script checks if URL has 'tm' parameter. If it has, then it sets bunch of tm_.. parameters and callback function. I don't know how they are used. User clicks something that triggers the tm_search_click Script sets new URL for the page and browser starts loading that Goto step 1.
contextmenu in webbrowser Windows Phone 7
i successfully added a contextmenu to my webbrowser with this javascript code: public void AttachContextMenu() { try { if ((App.Current as App).Browser.IsScriptEnabled) { (App.Current as App).Browser.InvokeScript("execScript", "function FindParentLink(item) \r\n{\r\n\tif (!item.parentNode)\r\n\t\treturn null;\r\n\tif (item.tagName.toLowerCase() == 'a') \r\n\t{\r\n\t\treturn item;\r\n\t} \r\n\telse \r\n\t{\r\n\t\treturn FindParentLink(item.parentNode);\r\n\t}\r\n}\r\n\r\nfunction FindParentImage(item) \r\n{\r\n\tif (!item.parentNode)\r\n\t\treturn null;\r\n\tif (item.tagName.toLowerCase() == 'img') \r\n\t{\r\n\t\treturn item;\r\n\t} \r\n\telse \r\n\t{\r\n\t\treturn FindParentImage(item.parentNode);\r\n\t}\r\n}\r\n\r\nfunction HandleContextMenu() \r\n{\r\n\tvar linkItem = FindParentLink(event.srcElement);\r\n var imageItem = FindParentImage(event.srcElement);\r\n var notifyOutput = '';\r\n if (linkItem != null) if (linkItem.href != null) notifyOutput += linkItem.href;\r\n if (imageItem != null) if (imageItem.src != null) notifyOutput += imageItem.src;\r\n if (notifyOutput != '')\r\n window.external.notify(notifyOutput);\r\n else\r\n\t\twindow.external.notify('NOTLINKIMG');\r\n}"); (App.Current as App).Browser.InvokeScript("execScript", "document.oncontextmenu = HandleContextMenu;"); } } catch { } } this method is used everytime the browser navigated. So, the scriptnotify code, which will be used when the user holds a link : if (e.Value.ToString() != null && IsValidUri(e.Value.ToString())) { ContextMenu cm = new ContextMenu(); MenuItem menuItem0 = new MenuItem() { Header = "X", Tag = e.Value }; menuItem0.Click += new RoutedEventHandler(X_Click); MenuItem menuItem1 = new MenuItem() { Header = "Y", Tag = e.Value }; menuItem1.Click += new RoutedEventHandler(Y_Click); MenuItem menuItem2 = new MenuItem() { Header = "Z", Tag = e.Value }; menuItem2.Click += new RoutedEventHandler(Z_Click); cm.Items.Add(menuItem0); cm.Items.Add(menuItem1); cm.Items.Add(menuItem2); ContextMenuService.SetContextMenu(Browser, cm); cm.IsZoomEnabled = false; cm.VerticalOffset = mouseClickPosition.Y; cm.IsOpen = true; } so far, i hope i made everything right. now, it randomly works. nearly 50% of tries cause a error, Visual studio navigates to a blue-white frame named "No source available" and throws a NullReferenceException. Where should this be solved? already set a try-catch block around the hole 2 method, no change :/ hope you have some ideas greets roqstr
don't got it working, but there's a workaround: AttachContextMenu() -> holding a link will push the url to the scriptnotify method. build a custom contextmenu & everything is fine.