13

I have some problem with posting formData to server side action method. Because ajax call doesn't send files to server, I have to add file uploader data to formData manually like this:

var formData = new FormData();
formData.append("imageFile", $("#imageFile").file);
formData.append("coverFile", $("#coverFile").file);

I wrote jQuery function that need to post form data to server using ajax call. It's works but posted formData in server side is always null!

this is my script:

    <script>
        function SubmitButtonOnclick()
        {    
            var formData = new FormData();
            formData.append("imageFile", $("#imageFile").file);
            formData.append("coverFile", $("#coverFile").file);

            $.ajax({
                type: "POST",
                url: '@Url.Action("EditProfile", "Profile")',
                data: formData,
                dataType: 'json',
                contentType: "multipart/form-data",
                processData: false,
                success: function (response) {
                    $('#GeneralSection').html(response.responseText);
                },
                error: function (error) {
                    $('#GeneralSection').html(error.responseText);
                }
            });
        }
    </script>

Edit 1: This is the action method in controller:

        public ActionResult EditProfile(ProfileGeneralDescription editedModel,
                                HttpPostedFileBase imageFile,
                                HttpPostedFileBase coverFile,
                                string postOwnerUser)
        {
            try
            {
                if (postOwnerUser == User.Identity.Name)
                {
                // edit codes...    
                    var result = GetProfileGeneralDescription(postOwnerUser);
                    return PartialView("_GeneralProfile", result);
                }
                else
                {
                    var error = new HandleErrorInfo(
                    new Exception("Access Denied!"),
                    "Profile",
                    EditProfile
                    return PartialView("~/Views/Shared/Error.cshtml", error);
                }
            }
            catch (Exception ex)
            {
                var error = new HandleErrorInfo(ex, "Profile", EditProfile
                return PartialView("~/Views/Shared/Error.cshtml", error);
            }
        }

Edit 2: Cshtml view file content:

@model Website.Models.ViewModel.Profile

    @using (Ajax.BeginForm("EditProfile", "Profile", new { postOwnerUser = User.Identity.Name }, new AjaxOptions()
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "GeneralSection"
    }, new { enctype = "multipart/form-data" }))
    {

        <div>
             <button id="btnSubmit" type="button" onclick="SubmitButtonOnclick()">Submit</button>
        </div>

        <input type="hidden" name="username" id="username" value="@Model.Username"/>

        <fieldset>
            <legend>Edit Photos</legend>
            <div>
                Select profile picture:
                <input id="imageFile" type="file" name="imageFile" accept="image/png, image/jpeg" />
                @Html.CheckBoxFor(modelItem => modelItem.DefaultCover)<span>Remove profile photo</span>
            </div>
            <div>
                Select cover picture:
                <input id="coverFile" type="file" name="coverFile" accept="image/png, image/jpeg" />
                @Html.CheckBoxFor(modelItem => modelItem.DefaultCover)<span>RemoveCover</span>
            </div>
        </fieldset>
    }

Any tips, link or code example would be useful.
Thank you in advance!

3

3 Answers 3

26

Instead of Jquery Ajax you could use

 <script>
            function SubmitButtonOnclick()
            { 
                var formData= new FormData();
                var imagefile=document.getElementById("imageFile").files[0];
                var coverfile=document.getElementById("coverFile").files[0];
                formData.append("imageFile",imageFile);
                formData.append("coverFile",coverFile);
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "/Profile/EditProfile", true);
                xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
                xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
                xhr.send(formData);

            }

      function UploadComplete(evt) {
        if (evt.target.status == 200) 
                alert("Logo uploaded successfully.");

        else 
                 alert("Error Uploading File");
        }

    function UploadFailed(evt) {
        alert("There was an error attempting to upload the file.");

    }
 </script>

This works for me !!

Your script with changes

 function SubmitButtonOnclick() {
        var formData = new FormData();
        var file = document.getElementById("imageFile").files[0];
        var file1 = document.getElementById("coverFile").files[0];
        formData.append("imageFile", file);
        formData.append("coverfile", file1);
        $.ajax({
            type: "POST",
            url: '@Url.Action("EditProfile","Default1")',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (response) {
                $('#GeneralSection').html(response.responseText);
            },
            error: function (error) {
                $('#GeneralSection').html(error.responseText);
            }
        });
    }
18
  • Thanks for your answer. My last code was like yours. But I need to post all data together and replace response text with current content that XHRdont do this exactly for me. How can I add success or error page to XHR request?
    – Mojtaba
    Dec 17, 2013 at 8:50
  • If it is success then UploadComplete function gets called.you can write your code in that method. if uploads fails then UploadFailed function gets called Dec 17, 2013 at 8:56
  • I copy/paste your code into my script section but it's steel sent null data to server side function. (success alert was shown in client side)
    – Mojtaba
    Dec 17, 2013 at 9:01
  • 1
    i have updated the answer...dont use jquery in that to append file Dec 17, 2013 at 10:51
  • 1
    Your advices was very helpfull @Nilesh. Thanks :-) It's finally works without post another data. Just this line: formData.append("imageFile", $("#imageFile").file); doesn't work and must be replaced by formData.append("imageFile", file); Thanks. :)
    – Mojtaba
    Dec 17, 2013 at 10:59
4
   <input type="file" id="picfile" name="picf" />
       <input type="text" id="txtName" style="width: 144px;" />
 $("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;

                    var file = document.getElementById("picfile").files[0];
                    formData.append("FileUpload", file);
                    formData.append("Name", Name);

$.ajax({
                    type: "POST",
                    url: '/Category_Subcategory/Save_Category',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (msg) {

                                 alert(msg);

                    },
                    error: function (error) {
                        alert("errror");
                    }
                });

});

 [HttpPost]
    public ActionResult Save_Category()
    {
      string Name=Request.Form[1]; 
      if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
         }


    }
0

I was able to upload file through jquery using the iframe, I explained the same in my blog post, please follow the link to get the answer.

http://kaushikghosh12.blogspot.com/2014/02/ajax-fileupload-on-all-browsers.html

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.