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

Community
  • 1
  • 1
Bloomberg58
  • 157
  • 1
  • 19
  • Your script is not correct. Refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) 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` –  May 03 '17 at 23:51
  • @StephenMuecke Reading http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/ 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) – Bloomberg58 May 04 '17 at 06: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) –  May 04 '17 at 06:49

0 Answers0