1

I am doing a file upload and my code is correct for the upload.

This example is pretty much exactly what I am doing: https://stackoverflow.com/a/15680783/5874935

HOWEVER, something has happened with my project and it has suddenly stopped working. I have worked and worked with no avail to fix the issue. I recently converted to a single page application using this function to submit a form:

 var ajaxFormSubmit = function (contentDiv, formDiv, modalId, formId, controllerPath) {
         $(".loader").show();
         $("#".concat(formId)).on("submit", function (e) {
             console.log("ajax form submitted");
             e.preventDefault();  // prevent standard form submission
             var form = $(this);
             $.ajax({
                 url: form.attr("action"),
                 method: form.attr("method"),  // post
                 data: form.serialize(),
                 error: function () {
                     $(".loader").hide();
                     alert("An error occurred.");
                 },
                 success: function (partialResult) {
                     console.log(partialResult.length);

                     if (partialResult.length === 0) {
                         console.log("form archhived");
                         $("#".concat(modalId)).modal('hide');
                         //forcing the backdrop to go away, something is wrong with the modal, it needs work.
                         $('.modal-backdrop').remove();
                         getManager(controllerPath, contentDiv);
                         //get gunnery manager
                     }
                     else {
                         console.log("form came back");
                         $("#".concat(formDiv)).html(partialResult);
                         $(".loader").hide();

                     }
                 }
             });
         });
     }

model:

public class person 
{
public int id {get;set;}
public string fName {get;set;}
public string lName {get;set;}
public HttpPostedFileBase attachment {get;set;}
}

here is my controller portion:

if (model.attachment != null)
                {
                    var file = model.attachment;
                        if (file.ContentLength > 0)
                        {

                            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"),Path.GetFileName(file.FileName));
                        file.SaveAs(path);
                        System.Diagnostics.Debug.WriteLine(path);
                        model.attachmentLink = path;
                    }

            }

I find it no conincidence that my file upload stopped working around this time, but I just now noticed. How do I make my file upload work?

NOTE The view is very standard using html helpers.

Community
  • 1
  • 1
Travis Tubbs
  • 827
  • 1
  • 14
  • 32
  • Was it working with $,ajax before? or it stopped working when you you added $.ajax.. As per my knowledge you can't upload file with AJAX unless you use FormData. – K D Jan 18 '17 at 16:04
  • stopped when I added AJAX, I THINK. I was originally using HTTP posts – Travis Tubbs Jan 18 '17 at 16:07
  • it means you need to add Form Data to make it work – K D Jan 18 '17 at 16:08
  • I have encType = "multipart/form-data"} in my html.beginForm in my html helper – Travis Tubbs Jan 18 '17 at 16:09
  • You need to use `FormData` (not the same thisng as `encType = "multipart/form-data"`) and set the correct ajax options in order to upload 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) for an example –  Jan 18 '17 at 21:07

1 Answers1

1

Try following using FormData

var ajaxFormSubmit = function (contentDiv, formDiv, modalId, formId, controllerPath) {
             $(".loader").show();
             $("#".concat(formId)).on("submit", function (e) {
                 console.log("ajax form submitted");
                 e.preventDefault();  // prevent standard form submission
                 var form = $(this);
                 var formData = new FormData(); // CREATE FORM DATA OBJECT
                 var fileUpload = $("#file").get(0); // your file element
                 var files = fileUpload.files;
                 formData.append("YOR_FILE_DATA_KEY_NAME", files[0]);
                 // add all form elements like following
                // formData.append("key",value);
                   formData.append("id",$("#id").val()); // check the selector if it is correct
                   formData.append("fName",$("#fName").val());
                   formData.append("lName",$("#lName").val());
                 $.ajax({
                     url: form.attr("action"),
                     method: "POST",  // post
                     contentType: false, // Not to set any content header
                     processData: false, // Not to process data
                     data: formData, // pass this form data instead of form.serialize()
                     error: function () {
                         $(".loader").hide();
                         alert("An error occurred.");
                     },
                     success: function (partialResult) {
                         console.log(partialResult.length);

                         if (partialResult.length === 0) {
                             console.log("form archhived");
                             $("#".concat(modalId)).modal('hide');
                             //forcing the backdrop to go away, something is wrong with the modal, it needs work.
                             $('.modal-backdrop').remove();
                             getManager(controllerPath, contentDiv);
                             //get gunnery manager
                         }
                         else {
                             console.log("form came back");
                             $("#".concat(formDiv)).html(partialResult);
                             $(".loader").hide();

                         }
                     }
                 });
             });
         }

EDIT: Solution to convert form.seralize() to FormData object

function ConvertToFormData(serializedArray, fileInputID)
{
var formData = new FormData();
//var serializedArray = $("form").serializeArray();
for(var i = 0; i < serializedArray.length;i++)
{
    if(serializedArray[i].name != "FILE_INPUT_ELEMENT") // don't add file input here
    formData.append(serializedArray[i].name,serializedArray[i].value);

}

var fileUpload = $(fileInputID).get(0); // your file element
                 var files = fileUpload.files;
                 formData.append(fileInputID, files[0]);
return formData;
}

How to use this function???

var data = ConvertToFormData($("form").serializeArray(),"Your_file_input_id");
K D
  • 5,889
  • 1
  • 23
  • 35
  • so what will form data do? will it allow this function to work with all of my other forms? I have never seen that – Travis Tubbs Jan 18 '17 at 16:13
  • 1
    If you have file upload in your form and you need that form to be posted by AJAX you have to use FormData(), if your forms doesn't include file upload, your existing solution should work fine . If you have lots of form with file upload, i will suggest to create common function/utility in javascript to handle all of them like this. – K D Jan 18 '17 at 16:16
  • check this post for illegal invocation and handle the error http://stackoverflow.com/questions/10324594/jquery-illegal-invocation – K D Jan 18 '17 at 16:17
  • basically, I have a model that is a registration application, and it has an image that the user can input with it. – Travis Tubbs Jan 18 '17 at 16:18
  • the solution in the answer should work for it .. just check and debug that all your form elements are getting added correctly to formdata object and it posts data to server on submit – K D Jan 18 '17 at 16:20
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/133472/discussion-between-travis-tubbs-and-k-d). – Travis Tubbs Jan 18 '17 at 16:27