0

I have zip file that I want to encode and send it as string and decode and save it in server side:

This the code of the encoding in client (JS):

var fileAsText = ''
var reader = new FileReader()
reader.onload = function (event) {
  fileAsText = encodeURIComponent(event.target.result)
}
reader.readAsText(zipFile)

zipFile is the input File object (uploaded by the user).

The fileAsText string I'm sending as Post inside JSON (this is the reason I'm using encodeURIComponent)

Everything works fine, but in server side I want to take this string and decode it back to binary (zip file) and extract it. and I want to get exactly the same file the user upload in client side.

This is my code in c#:

 using (var bw = new BinaryWriter(File.Open("fileTest.zip", FileMode.Create)))
 {
      bw.Write(HttpUtility.UrlDecode(fileAsText));
 }

The problem: I don't get the same file (the binary data is diffrent) I believe the decoder HttpUtility.UrlDecode is not fit to encodeURIComponent

Any idea how to get the same file binary data uploaded by the user?

cheziHoyzer
  • 4,803
  • 12
  • 54
  • 81
  • 2
    You probably shouldn't read it as text... just send the blob as is... and then use formData to combine both json and files. From the moment you did read it as text using filereader you have gotten a broken data. Javascript can't handle binary strings so well – Endless Oct 26 '16 at 17:16
  • @Endless I know, there is a reason I read it as text, it's complicated to explain (it's limitation) please find a solution if I have to use reader.readAsText Thanks – cheziHoyzer Oct 26 '16 at 17:20
  • Why do you need to post it as json? It's a bad idea. you can send it as it's `xhr.send(zipFile)` or use multipart upload if you need more fields ([FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData)) – Endless Oct 26 '16 at 17:27
  • I'm using Json RPC as communication https://github.com/Astn/JSON-RPC.NET so I can send only Json to the server. I can't send File to the server – cheziHoyzer Oct 26 '16 at 17:34
  • Then i suggest you read is `asDataURL` (base64) but that will give you a overhead and ~3x more bandwidth – Endless Oct 26 '16 at 17:37
  • And how decode it in c#? – cheziHoyzer Oct 26 '16 at 17:47
  • http://stackoverflow.com/questions/7134837/how-do-i-decode-a-base64-encoded-string – Endless Oct 26 '16 at 17:47
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126759/discussion-between-chezihoyzer-and-endless). – cheziHoyzer Oct 26 '16 at 18:02

1 Answers1

2

Binary string don't work well in javascript best would be to post it as multipart form data.

But if you really need to post it as json cuz of some server restriction then the best is to send it as base64

A quick fix is just changing readAsText to readAsDataURL Then on the server side convert it back to binary using Convert.FromBase64String

byte[] data = Convert.FromBase64String(encodedString);
Endless
  • 34,080
  • 13
  • 108
  • 131