Reputation: 1
I am trying to parse a csv file, but this file format is in ANSI. So when I print out the result on page, it looks like below: ANSI file output
and I use following code in my test php file to convert the string:
iconv(mb_detect_encoding($str, mb_detect_order(), true), "UTF-8", $str);
then it looks normal now as this:
But I'd like to do the conversion on front side, using js, so is there any way to convert the string to utf-8 format like php method -> iconv().
Thanks.
Upvotes: 0
Views: 2401
Reputation: 1403
Here is a sample code on reading one file using a file input control and displays the first line along with some of the file's properties:
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
alert( "Got the file.n"
+"name: " + f.name + "n"
+"type: " + f.type + "n"
+"size: " + f.size + " bytesn"
+ "starts with: " + contents.substr(1, contents.indexOf("n"))
);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
You can use Reading Files Using The HTML5 FileReader API. It is pointless to try to convert the file after contents were ruined when trying to load in a wrong encoding.
Try looking into below articles if you want to go deep down:
Upvotes: 1