HttpPostedfileBase is null using jQuery Ajax

前端 未结 3 1829
萌比男神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 <form enctype="multipart/form-data"></form> 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)
    {
    }
    
    0 讨论(0)
  • 2020-12-28 16:35

    View:

    <script/>
    var add_photo_url = "@Url.Action("AddPhoto", "Gallery")"; 
        var model = new FormData();    
        var i=0;//selected file index 
        model.append("File", files[i]);
        model.append("Name", "test");
        $.ajax({// and other parameter is set here 
            url: add_photo_url,
                type: "POST",
                data: model,
                dataType: "json",
                cache: false,
                contentType: false,
                processData: false
    
            })
            .always(function (result) { 
            });
    </script>
    

    View Model:

    public class PhotoAlbumViewModel {
        public  string Name { get; set; }
        public HttpPostedFileBase File { get; set; }
    }
    

    Controller:

    public JsonResult AddPhoto(PhotoAlbumViewModel model) {
        // var result =...
        // and set your result; 
        return Json(result, JsonRequestBehavior.AllowGet);
    }
    
    0 讨论(0)
  • 2020-12-28 16:36

    I have modified @a moradi's answer.

    JS:

    //FormData:
    //Consider it a normal form but with "multipart/form-data" encoding type.
    //Inside it works same as XMLHttpRequest.send() method.    
    var model = new FormData();
    model.append("File", $('#file')[0].files[0]);
    model.append("Name", "Name");
    $.ajax({ 
            url: someUrl,
            type: "POST",
            data: model,
            //contentType: 
            //Sets the ContentType in header.
            //The default contentType is "application/x-www-form-urlencoded; charset=UTF-8". But this will prevent us sending AntiForgeryToken to service/controller.
            //To prevent this contentType is set to false.
            contentType: false,
            //processData:
            //To prevent data getting converted to string format, 'processData' option is set to false.
            processData: false,
            success = function (m) {...}
            error = function (m) {...}
        });
    

    View Model:

    public class PhotoAlbumViewModel {
        public  string Name { get; set; }
        public HttpPostedFileBase File { get; set; }
    }
    

    Controller:

    public JsonResult AddPhoto(PhotoAlbumViewModel model) {
        ...
    }
    

    Refrence:

    Reffer following links for details: FormData , JQuery , ContentType

    0 讨论(0)
提交回复
热议问题