We have a client-side control where a user will be able to upload any filetype. The form is serialized into a FormData object and the file is then posted to the server with an ajax call.
var data = new FormData($("#myform")[0]);
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false,
cache: false,
success: function (d, s, x) { },
error: function (x, s, e) { },
complete: function (x) { }
});
In the receiving controller for the posted file, we are creating a new instance of HttpPostedFile
based on the HttpRequest.Files
collection, and then reading the InputStream
into a byte[]
.
HttpPostedFile file = Request.Files[0];
byte[] fileData = null;
string fileStream;
file.InputStream.Position = 0;
using (var reader = new BinaryReader(file.InputStream, System.Text.Encoding.UTF8))
{
fileData = reader.ReadBytes(file.ContentLength);
}
After the byte[]
has been set, we perform a UTF8.GetString()
call on the binary data in order to get the string representation.
fileStream = System.Text.Encoding.UTF8.GetString(fileData);
The issue we are having is that the data of fileStream
looks invalid as it contains questionmark replacement characters for some characters.
The reason why we are trying to convert the binary data into its string representation, is to store the value of the uploaded file in a database for further use.
What are we missing please?