0

I'm trying to upload my image with the help of Jquery . But it seems I'm missing out something. In my View I've this:-

 $(document).ready(function () {
    $('#ImageSave').click(function () {
        var Image = $("#File").val();
        var Alt = $("#Alt").val();
        var ImgGroup = $("#ImgGroup").val();
        var Year = $("#Year").val();
        var Description = $("#Description").val();

        var ImgID = {
            "Image": Image, "Alt": Alt,
            "ImgGroup": ImgGroup, "Year": Year, "Description": Description
        };
        $.post("/Admin/ImageCreate", ImgID,
        function (data) {
            if (data == "Success") {
                alert('Image Added Successfully!!');
            }
            else if (data == "Failed") {
                alert('Image Not Added!! Please Fill all Details or Contact Support')
            }

            else {
                alert(data);
            }
        }, 'json');

    });
});

@using (Html.BeginForm(new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend></legend>
        <div class="editor-label">
            Image Group
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ImgGroup)
            @Html.ValidationMessageFor(model => model.ImgGroup)
        </div>
        <div class="editor-label">
            Year
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Year)
            @Html.ValidationMessageFor(model => model.Year)
        </div>
        <div class="editor-label">
            Description
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>
        <div class="editor-label">
            Image
        </div>
        <div>
            <input id="File" title="Upload an image" type="file" name="file" class="btn btn-info" />
            @Html.ValidationMessageFor(model => model.Image)
        </div>
        <div class="editor-label">
            Alternative Description
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Alt)
            @Html.ValidationMessageFor(model => model.Alt)
        </div>
        <p>
            <input id="ImageSave" type="button" value="Create" />
        </p>
    </fieldset>
}

In my Controller I've two Results for GET and POST:-

[HttpGet]
[LogInFilter]
public PartialViewResult ImageCreate()   //Insert PartialView  
{
    return PartialView(new GarhwalBhawan.Models.ImageTbl());
}

[HttpPost]
[LogInFilter]
public JsonResult ImageCreate(GarhwalBhawan.Models.ImageTbl ImgObj, HttpPostedFileBase file) // Record Insert  
{
    if (ModelState.IsValid)
    {
        if (file != null)
        {
            file.SaveAs(HttpContext.Server.MapPath("~/Image/") + file.FileName);
            ImgObj.Image = file.FileName;
        }

        db.ImageTbls.Add(ImgObj);
        db.SaveChanges();
        myMessage = "Success";
    }

    else
    {
        myMessage = "Failed";
    }
    return Json(myMessage, JsonRequestBehavior.AllowGet);
}    

Now when I click the Create Button. The record is saved with an anonymous path as 'C:\fakepath\22012012014.jpg' and the debugger shows that I don't have any file while saving in file.saveas. I can't figure out the error.

Deepak
  • 376
  • 6
  • 23
  • You have to use `FormData` to post files using ajax - refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Oct 30 '16 at 07:02
  • I'm a little lost. How to do it with Html.BeginForm(). Also I don't want to change to $.ajax can I do it with current context i.e $.post method? – Deepak Oct 30 '16 at 07:29
  • What do you mean - `$.post()` is just a shortcut for `$.ajax()` - Read the answer I linked to. You need to use `FormData` and you nee to set the correct ajax options –  Oct 30 '16 at 07:31
  • Okay. But how will my controller map the correct HTMLcontrol in HTML to columns in model? – Deepak Oct 30 '16 at 07:52
  • FGS, Did you even bother to read the link and try it! –  Oct 30 '16 at 07:53
  • Yes, I did. I'm sorry I'm new to ajax and mvc. I can't understand the how can I apply the solution in the link to my code. – Deepak Oct 30 '16 at 07:56
  • Exactly as per the code in that answer (now a dupe) - `var formdata = new FormData($('form').get(0));` serializes all your form controls including the file input (exactly as explained in the dupe). Then the code in the second snippet (`$.ajax({ ...` sends to to your method and it will all be correctly bound –  Oct 30 '16 at 08:02
  • With reference to the linked question I changed javascript function as:- var formdata = new FormData($('form').get(0)); $(document).ready(function () { $('#ImageSave').click(function () { $.ajax({ url: '@Url.Action("ImageCreate", "Admin")', type: 'POST', data: formdata, processData: false, contentType: false, }); }); }); – Deepak Oct 30 '16 at 10:40
  • `var formdata = ...` needs to be inside the `$('#ImageSave').click(function () {` function. And if your still having problems, then edit your question by appending the new code you have tried (or ask a new question with the relevant code) - not in comments –  Oct 30 '16 at 10:43
  • But my controller is getting all values as null on submit. – Deepak Oct 30 '16 at 10:48
  • It certainly will if you have declared `var formdata = ...` before the `$('#ImageSave').click(function () {` And you need to learn to debug your code (but I have told you that before) –  Oct 30 '16 at 10:51
  • Oh Yeah!! Putting var formdata = ... inside the $('#ImageSave').click(function () { function solved that problem. Thanks A Lot!! You have been very helpfull! A big thanks – Deepak Oct 30 '16 at 10:51

1 Answers1

1

You need to extract only the filename without the path from the uploaded file:

var fileName = Path.GetFileName(file.FileName);
file.SaveAs(HttpContext.Server.MapPath("~/Image/") + fileName);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928