HttpPostedfileBase is null using jQuery Ajax

前端 未结 3 1837
萌比男神i
萌比男神i 2020-12-28 15:50

I have problem with uploading file In Asp.net Mvc. First of all I should use Ajax to pass the upload file value.

In javascript I have model that I fill it, When I c

3条回答
  •  梦谈多话
    2020-12-28 16:34

    First, it's possible to upload with Ajax, the important thing is you need to set

    on you form to tell it your form has an file upload input. Then you need to accept HttpPostedFileBase as an input parameter in your controller action.

    Try this. Example of jquery upload code. (Taken mostly from How can I upload files asynchronously?)

    function uploadFile(uploadId) {
        var formData = new FormData($('form')[0]);
    
        $.ajax({
            url: '<%= Url.Action("SaveOneDatabase")%>',
            type: 'Post',
            beforeSend: function(){},
            success: function(result){
    
            },
            xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload) { // Check if upload property exists
                    // Progress code if you want
                }
                return myXhr;
            },
            error: function(){},
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
    }
    

    HTML Form needs this attribute. See this post why you need it -> What does enctype='multipart/form-data' mean?

    enctype="multipart/form-data"
    

    C#

    [HttpPost]
    public ActionResult SaveOneDatabase(HttpPostedFileBase file)
    {
    }
    

提交回复
热议问题