2

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...

3
  • Your script is not correct. Refer this answer for uploading a file with additional data (you need to .append() the id value to FormData. And the parameter in the POST method need to be HttpPostedFileBase imageUploadForm Commented May 3, 2017 at 23:51
  • @StephenMuecke Reading haacked.com/archive/2010/07/16/… I saw how to access a file (or files) in HttpPostedFileBase in my action. But since I'll appen to formData some other simple properties (string, double, date, etc..), how will I access them in the controller ? (I did not see that in your earlier answer) Commented May 4, 2017 at 6:46
  • 1
    You already have a parameter int id which will be bound to the id value in FormData (but you really should be using a view model) Commented May 4, 2017 at 6:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.