javascript sendfile binary data to web service

2019-09-13 17:07发布

问题:

At work we are trying to upload files from a web page to a web service using html 5/javascript in the browser end and C# in the web service. But have some trouble with encoding of some sort.

As for the javascript we get the file's binary data with help from a FileReader.

var file = ... // gets the file from an input
var fileReader = new FileReader();
fileReader.onload = dataRecieved;
fileReader.readAsBinaryString(file);

function dataRecieved() {
  // Here we do a normal jquery ajax post with the file data (fileReader.result).
}

Wy we are posting the data manually and not with help from XmlHttpRequest (or similar) is for easier overall posting to our web service from different parts of the web page (it's wrapped in a function). But that doesn't seem to be the problem.

The code in the Web Service looks like this

[WebMethod]
public string SaveFileValueFieldValue(string value)
{
  System.Text.UnicodeEncoding encoder = new UnicodeEncoding();
  byte[] bytes = encoder.GetBytes(value);
  // Saves file from bytes here...
}

All works well, and the data seems to be normal, but when trying to open a file (an image as example) it cannot be opened. Very basic text files seems to turn out okay. But if I upload a "binary" file like an image and then open both the original and the uploaded version in a normal text editor as notepad to see what differs, it seems to be wrong with only a few "invisible" characters and something that displays as a new line a few bytes in from from the start.

So basicly, the file seems to encode just a few bytes wrong somewhere in the conversions.

I've also tried to create an int array in javascript from the data, and then again transformed to a byte[] in the web service, with the exact same problem. If I try to convert with anything else than unicode (like UTF-8), the data turns out completly different from the original, so I think om on the right track here, but with something slightly wrong.

回答1:

The request itself is text, so binary data is lost if you send the wrong enc-type. What you can do is encode the binary to base64 and decode it on the other side.
To change the enc-type to multi-part/mixed and set boundaries (just like an e-mail or something) you'd have to assemble the request yourself.