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?

8
  • 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 Commented Oct 26, 2016 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 Commented Oct 26, 2016 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) Commented Oct 26, 2016 at 17:27
  • I'm using Json RPC as communication github.com/Astn/JSON-RPC.NET so I can send only Json to the server. I can't send File to the server Commented Oct 26, 2016 at 17:34
  • Then i suggest you read is asDataURL (base64) but that will give you a overhead and ~3x more bandwidth Commented Oct 26, 2016 at 17:37

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.