I have utilized a different approach by not using the HttpPostedFileBase
to retrieve content from the MVC application. Instead, I opted for JSON.
One can easily utilize the FileReader.onload
method in HTML5 to extract file content and transmit it as a Base64 string directly to the MVC controller. The #upload-button
represents an <input type=file ...>
tag.
var file = $('#upload-button')[0].files[0];
var reader = new FileReader();
reader.onload = (function (f) {
return function (e) {
if (e.target.readyState == FileReader.DONE) {
$.ajax("FileStore/SavePicture", {
data: { content: e.target.result, name: f.name },
type: "post",
contentType: "application/json"
});
}
};
})(file)
Subsequently, one can employ the Convert.FromBase64String
method to convert it to a byte[]
. Here is an example of how the Action content appears:
string base64String = content;
// Locate the position of the real content within the base64String.
int start = base64String.IndexOf(",") + 1;
int length = base64String.Length - start;
contentAsString = base64String.Substring(start, length);
byte[] dataAsBytes = Convert.FromBase64String(contentAsString);
There may exist alternative methods to achieve the same functionality.