简体   繁体   中英

Javascript - sending encoding binary (zip) file data and decoding it in c#

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM