I have a database with a varbinary(max)
column for storing an image. I'd like to save the image in the database using Ajax (with controller actions and Entity Framework). Further, I'd like to retrieve the saved image and display it on the view (but that's another problem).
After looking around, I saw this https://stackoverflow.com/a/25768212/7885071
From that answer I have the following Ajax function :
function SaveImageViaAjax() {
var id = 123;
var formData = new FormData();
var totalFiles = document.getElementById("imageUploadForm").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("imageUploadForm").files[i];
formData.append("imageUploadForm", file);
}
$.ajax({
type: "POST",
data: {
"id":id
"image": formData
},
url: '/MyController/MyAction/',
success: function (response){
// alert(success);
},
error: function (xhr, status, error) {
alert("error");
}
});
}
If that function is correct, my problem is I don't know how to use an Action to populate/read the database.
Using https://stackoverflow.com/a/25400976/7885071 , I have properly set my model with byte[]
for the image but how to deal with the action?
Here is what I propose :
Action to save the image in database:
[HttpPost]
public string SaveImageFromAjax(int id, byte[] image) //same as Ajax data section...
{
using(var db = myDbContext())
{
var MyObject object1 = new MyObject();
object1.id = id;
obecjt1.photo = image;
db.MyObject.Add(object1);
db.SaveChanges();
}
return "my message";
}
I know I must be far from the right code. Hopefully you'll kindly guide me to it...