我的文件上传停止了

时间:2017-01-18 16:02:12

标签: jquery asp.net ajax asp.net-mvc form-data

我正在进行文件上传,我的代码对于上传是正确的。

这个例子正是我正在做的事情:https://stackoverflow.com/a/15680783/5874935

然而,我的项目发生了一些事情,它突然停止了工作。我工作和工作没有用到解决问题。我最近使用此函数转换为单页应用程序以提交表单:

 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();

                     }
                 }
             });
         });
     }

模型:

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

这是我的控制器部分:

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;
                    }

            }

我发现我的文件上传在这个时候停止工作并不是巧合,但我刚才注意到了。如何使文件上传工作?

注意 使用html帮助程序非常标准。

1 个答案:

答案 0 :(得分:1)

请尝试使用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();

                         }
                     }
                 });
             });
         }

编辑:将form.seralize()转换为FormData对象的解决方案

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;
}

如何使用此功能???

var data = ConvertToFormData($("form").serializeArray(),"Your_file_input_id");