Reputation:
I am writing code using knockoutjs and mvc5 where an image is selected on the ui and the binary of the image is uploaded via ajax.
I cant really show much surrounding the image upload, but I know it works. The image is local to the browser and the binary is stored in the view model.
The problem is uploading this binary to mvc.
In my javascript, I am constructing a post using the following:
var customerData = {
CustomerName: self.CustomerName(),
CustomerImage: self.CustomerImage().imageBinary(),
CustomerJobNumber: self.CustomerJobNumber()
};
//If add, enable remaining area, change id, and start customer edit
if (window.location.hash == "#customer-add") {
$.ajax({
type: 'POST',
url: "/Customer/SaveNew",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(customerData),
success: function(data) {
/*CODE*/
var title = data.title;
var msg = data.message;
if (data.success == 0) {
//growl as to why
} else {
//growl success
window.location.hash = "#customer-edit-" + data.newCustomer.CustomerId;
self.SetCustomerFields(data.newCustomer);
self.LoadCustomers();
}
},
error: function(err) {
alert(err);
//growl
}
});
}
And in my controller I have:
public class NewCustomerData
{
public string CustomerName { get; set; }
public byte[] CustomerImage { get; set; }
public string CustomerJobNumber { get; set; }
}
[HttpPost]
public ActionResult SaveNew(NewCustomerData data)
{
//Does stuff
}
When I break into the javascript running, the CustomerImage object that I am sending is of type ArrayBuffer. If I convert it to an Uint8Array I can verify there are contents. But the binary never appears in the controller.
Am I not assigning the correct c# object?
Upvotes: 1
Views: 1683
Reputation:
My solution to this was to convert the ArrayBuffer in the JavaScript to a Base-64 encoded string. I then modified the object on the server side to accept a string and voila.
Upvotes: 2