2

I'm building a file saver from a string using FileSaver.js from a SO question

let byteChars = atob("my string");
let byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++) {
  byteNumbers[i] = byteChars.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
var data:Blob = new Blob([byteArray], {type: "application/octet-stream"});
var filename:string = filename + '.myext';
saveAs(data, filename, true);

Then I have to read it back to "my string" using Javascript's FileReader:

let fr = new FileReader();
fr.onload = (e:FileReaderEvent) => {
    let result:any = e.target.result;
    //I don't know what I have to do with this type of data to get "my string" back
    };
fr.readAsBinaryString(file);
Community
  • 1
  • 1
Nam Pham
  • 1,224
  • 13
  • 38
  • 1
    Why are you base64 decoding "my string" here: `atob("my string");` ? – Alexander O'Mara Jun 30 '16 at 02:06
  • I got it from http://stackoverflow.com/a/23452051/5480251 this, I'm not sure if I can eliminate it, but "my string" here is the result from CryptoJS return for me, it has been encrypted. – Nam Pham Jun 30 '16 at 02:08
  • _"but save as binary in javascript"_ What do you mean by "binary" here? What is purpose of using `Uint8Array`, `Blob`, `'.myext'` file extension? You could save text content as file using `data URI` – guest271314 Jun 30 '16 at 02:18
  • @guest271314 It mean I don't want to save my text as plain text, `.myext` is a file extension. – Nam Pham Jun 30 '16 at 02:24
  • Is requirement to save text as `base64` string? – guest271314 Jun 30 '16 at 02:26
  • @guest271314 I want to save it as binary file, which is not readable for human but for the machine – Nam Pham Jun 30 '16 at 02:28

1 Answers1

2

Edit, Updated

write file

let byteChars = atob("my string");
let byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++) {
  byteNumbers[i] = byteChars.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
var data = new Blob([byteArray], {type: "application/octet-stream"});
saveAs(data, "myfile.abc");

read file

<input type="file">
<script>
 var reader = new FileReader();
 reader.addEventListener("load", function(e) {
   document.body.innerHTML += "<br>" + btoa(e.target.result);
 });
  document.querySelector("input[type=file]")
  .addEventListener("change", function(e) {
     reader.readAsBinaryString(e.target.files[0])
  })
</script>

plnkr http://plnkr.co/edit/0KVhXnd0JpysplDLcAlC?p=preview


You can use TextEncoder(), TextDecoder() or FileReader(), .readAsBinaryString()

var str = "my string";
var encoder = new TextEncoder();
var encodedBytes = encoder.encode(str);
// do file save stuff
var decoder = new TextDecoder();
var decodedBytes = decoder.decode(encodedBytes);

console.log(encodedBytes, decodedBytes);

// alternatively, using `FileReader()`
var reader = new FileReader();
reader.onload = function() {
  console.log("FileReader result:", reader.result)
}
reader.readAsBinaryString(new Blob([encodedBytes]))
guest271314
  • 1
  • 15
  • 104
  • 177
  • Hi, after do that, i got string like this: `U2FsdGVkX19F/TFrAgVg1vqS1eO1UXbDjYLY`, can it convert to some thing like this `ÊÀ,V˜õèeò+p¢¶ó¯£·ªÞY®Õß.`? – Nam Pham Jun 30 '16 at 02:46
  • _"Hi, after do that, i got string like this: U2FsdGVkX19F/TFrAgVg1vqS1eO1UXbDjYLY, can it convert to some thing like this ÊÀ,V˜õèeò+p¢¶ó¯£·ªÞY®Õß."_ What is "like this" string? How did did you retrieve the characters? – guest271314 Jun 30 '16 at 02:51
  • I mean it still a readable string, not like this http://www.directupload.net/file/d/4402/oju5gjbo_png.htm – Nam Pham Jun 30 '16 at 02:55
  • Where was string at linked image retrieved from? – guest271314 Jun 30 '16 at 02:58
  • Yes I do, and I get string like `U2FsdGVkX19F/TFrAgVg1vqS1eO1UXbDjYLY` when I save to file and open it to read. I mean the type of string, not the data itself – Nam Pham Jun 30 '16 at 03:19
  • It is possible to retrieve original string back, though space character `" "` at `"my string"` would not be preserved. There is probably a method which would maintain space character. Would a solution which returns `"mystring"` at `FileReader` meet requirement? – guest271314 Jun 30 '16 at 03:51
  • Yes, I can get it back and start to work, but I need it presents as binary instead of encoded string. – Nam Pham Jun 30 '16 at 14:40
  • @NamPham _"but I need it presents as binary instead of encoded string"_ What do you mean by "binary instead of encoded string"? [`TextEncoder().encode()`](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/encode) returns a [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays/Uint8Array) which is a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#Syntax) _"A TypedArray object describes an array-like view of an underlying binary data buffer."_ – guest271314 Jun 30 '16 at 15:09
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/116148/discussion-between-nam-pham-and-guest271314). – Nam Pham Jul 01 '16 at 02:10