sahithi
sahithi

Reputation: 1

Unable to save image into my sql database

My task is to save image into the database dynamically,whenever the user browses the img and clicks save button I am using asp.net mvc3,razor view and mysql is my database I am trying to pass the browsed img file to the controller and there in the controller i am converting it into byte format and save it into the db.But when i put a braekpoint it is showing null,indicating that the file is not pasing to the controller Could anyone please help me out in this

Below is my View and Controller

$(document).ready(function () {

       $("#photos").kendoUpload(); 
       $("#save").click(function (event) {   
           alert("started");
           url = 'Home/Details'; 
           var b;

           $.ajax({

               type: "POST",

               url: '/Home/Details',
               data: { b: $('#photos').load(url) }, 

               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function (str) {
                   alert("hai");
                   alert(str.st);
               }
           });



       });

   });

Controller:

     public ActionResult Details(HttpPostedFileBase b)
    {

        try
        {
           b = Request.Files[1];
            byte[] imageSize = new byte[b.ContentLength];
            b.InputStream.Read(imageSize, 0, (int)b.ContentLength);
            Image g = new Image();



            g.Img = imageSize;

            dbContext.Add(g);
            dbContext.SaveChanges();
            return RedirectToAction("Index");
        }
        catch
        {
        }
        var str = new { st = "saved" };
        return Json(str, JsonRequestBehavior.AllowGet);
    }

}

Upvotes: 0

Views: 295

Answers (2)

Beenish Khan
Beenish Khan

Reputation: 1583

Firstly I don't think you can submit file using Ajax since it is against JavaScript security model. You will need to use some other way for posting it ajax way. Here are some JQuery plugin for ajax file upload :

http://www.webdeveloperjuice.com/2010/02/13/7-trusted-ajax-file-upload-plugins-using-jquery/

If you want to use normal form post then you would have to set form element's encrypt property to "multipart/formdata" else the server just send file name and not the file itself.

Upvotes: 1

Marc B
Marc B

Reputation: 360902

  1. You cannot upload files via standard AJAX
  2. The return value of .load() is NOT the content loaded - it returns the jquery object. So you're trying to post the jquery object, NOT image data.

Upvotes: 0

Related Questions