Search code examples
jqueryajaxasp.net-mvcasyncfileupload

uploading file using jquery ajax - null issue


I have been trying this for a couple of hours now without making any headway. Here is the issue: I am trying to upload a file using jquery ajax. On the client side, it seems fine when I debug: I can see the file object, its name, its size, etc.

On the server side, the HttpPostedFileBase request is always null. Below is the code:

    //client side    
    <input type="file" style="visibility:hidden; height:0; width:0;" id="taskFileUpload"/>

    //triggered by file input change event
    var uploadFile = function (model, e) {
     fileUploadRequest('api/uploadFile',e.target.files[0]);
    }

   //so far seems good when debugging    
    var fileUploadRequest = function (url, file) {
             $.ajax({
                 url: url,
                 type: "POST",
                 data: file,
                 processData: false
             });


 //server side - request is always null!
 [AcceptVerbs("Post")]
 [AllowAnonymous]
 public HttpResponseMessage uploadFile(HttpPostedFileBase request)
 {
    return Request.CreateResponse(HttpStatusCode.OK, request);
 }

EDIT: I figured out the issue. The FormData approach as suggested below wasn't working for me for a different reason: Error 415 Media Type not supported. This had to do with .Net not knowing how to bind to HttpPostedFileBase object. So I did the following and it seems to work:

public HttpResponseMessage uploadFile()
        {
            var file = HttpContext.Current.Request.Files.Count > 0 ?
                HttpContext.Current.Request.Files[0] : null;
            return Request.CreateResponse(HttpStatusCode.OK);
        }

Solution

  • Show this example

    function subirArchivo() {
    var data = new FormData();
    var files = $("#fuArchivo").get(0).files;
    // Si se tiene archivo se va a guardar
    if (files.length > 0) {
        data.append("Archivo", files[0]);
    }
    var ruta = '';
    // Make Ajax request with the contentType = false, and procesDate = false
    var ajaxRequest = $.ajax({
        type: "POST",
        url: "../ServicioValidaciones.asmx/subirArchivo",
        contentType: false,
        processData: false,
        data: data,
        success: function (result) {
            ruta = result;
        },
    });
    ajaxRequest.done(function (xhr, textStatus) {
    // Make Ajax request with the contentType = false, and procesDate = false
    });
    

    }