0

I'm having issue creating new object into my database when I'm trying to include image within it.

My model:

    public Dog()

    {

    public int Id { get; set; }
    public string Name { get; set; }
    public string DogImageUrl { get; set; }

    }

my HTML code:

 @if (User.Identity.IsAuthenticated)
    {
          <h7>New Dog</h7>
            <input id="dogName" type="text" placeholder="dog name" />

                <input type="file" name="file" style="width: 100%;" />

                <input id="createNewDog" type="button" value="Go" />


            </div>
        </div>
    }

My Ajax post code: $('#addNewDog').click(function (e) {

         var imgToUpload = $("input[name=file]").get(0).files[0];
         var data = {
                "Name": $('#dogName').val(),
                "DogImageUrl ": "nullForNow",


            };
            var url = "@Url.Action("NewDog", "Home")";
            $.ajax({
                url: url,
                data: { model: data, file: Request.File[imgToUpload] },
                cache: false,
                type: "POST",
                contentType: "multipart/form-data",
                processData: false,
                success: function (respone) {
                    alert(respone);
                    location.reload();
                },
                error: function (reponse) {
                    alert(reponse);
                }
            });
            e.stopPropagation();
        });

my controller:

 public ActionResult NewDog(Dog model, HttpPostedFileBase file)
    {


        using (var contex = new DogContext())
        {
            if (User.Identity.IsAuthenticated)
            {

                if (file != null)
                {
                    try
                    {
                        if (file.ContentType == "image/jpeg")
                        {
                            if (file.ContentLength < 500000)
                            {
                                string pic = System.IO.Path.GetFileName(file.FileName);
                                string path = System.IO.Path.Combine(
                                                       Server.MapPath("~/Content/GroupImages"), pic);
                                // file is uploaded
                                file.SaveAs(path);
                                model.DogImageUrl = path;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        return Content(ex.ToString());
                    }
                }

                contex.Dogs.Add(model);
                contex.SaveChanges();
            }
        }

My img always comes null.. I searched all over the internet and didn't figure it out. the goal is to save the PATH to my image in my database.

Elkayam Gabay
  • 45
  • 2
  • 10
  • 1. You're not likely to get an actual path from the client's computer -- browsers often obfuscate the actual path. 2. Are there any script errors in the debug console? 3. See [jQuery Ajax File Upload](https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload) and the more [MVC specific](https://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc). – Jasen Aug 26 '17 at 21:01
  • @Jasen the idea is to save the path from the server, user uploads image, it saves it in my server and I want to get the path to it in the "DogImageUrl" – Elkayam Gabay Aug 26 '17 at 21:04
  • The second link demonstrates how to post the image rather clearly. – Jasen Aug 26 '17 at 21:09
  • @Jasen I saw this few horus ago but didn't understand how to implement it in my code, could you help me please? – Elkayam Gabay Aug 26 '17 at 21:11

1 Answers1

0

First you define your model

public class DogUpload
{
    public int Id { get; set; }
    public string Name { get; set; }
    public HttpPostedFileBase Image { get; set; }
}

Then your action

[HttpPost]
public ActionResult Upload(DogUpload model)
{
    var image = model.Image;
    var name = model.Name;
    var fileName = image.FileName;

    var path = Server.MapPath("~/Content/GroupImages" + fileName);
    image.SaveAs(path);

    // create valid url to dog image
    // create Dog and save to database
    var dog = dbContext.Dogs.FirstOrDefault(d => d.Id == model.Id);
    if (dog == null)
    {
       dog = new Dog
       {
           Name = model.Name,
           DogImageUrl = url
       };
       ...
    }

    return Json(new { message = "Created", id = dog.Id, name = dog.Name, url = dog.DogImageUrl });
}

Your view

@using(Html.BeginForm("Upload", "Dog", FormMethod.Post,
       new { id="dogForm", enctype="multipart/form-data" })
{
    <input type="file" name="Image" />
    <input type="text" name="Name" />
    <button type="submit">Submit</button>
}

The AJAX

$("#dogForm").on("submit", function(e) {
    e.preventDefault();

    var form = $(this);
    var formData = new FormData(form.get(0));

    $.ajax({
        url: form.attr("action"),
        method: form.attr("method"),
        data: formData,
        processData: false,
        contentType: false
    })
    .then(function(result) {
        console.log(result);
    });
});
Jasen
  • 14,030
  • 3
  • 51
  • 68
  • I appreciate your answer, but my goal is to save the image path (which should be stored in my server) in my dog model, and not the image itself as you updated the model – Elkayam Gabay Aug 26 '17 at 22:35
  • "My img always comes null" which image is always null? – Jasen Aug 26 '17 at 22:41
  • the one I'm trying to upload :/ it comes to the controller null – Elkayam Gabay Aug 26 '17 at 23:01
  • Your example forces me to change my class, I don't want my dog to have Image field, I want it to have string that contains path to the image – Elkayam Gabay Aug 26 '17 at 23:36
  • There are two dog classes -- one to upload the data to your server, and the other to persist the data in the database (your entity). There's no reason to change your entity class. But you also should not try to force that entity to handle the upload task. Make a new class to upload the data. – Jasen Aug 26 '17 at 23:58
  • And how will I link the path to the correct entity? got me confused much – Elkayam Gabay Aug 27 '17 at 00:05