How can I get a posted file on server-side from an Ajax Request in asp.net-webpages?

VoidKing picture VoidKing · Oct 9, 2013 · Viewed 8.7k times · Source

Using the helpful information I found here:

How can I upload files asynchronously?

I was able to get form data to the server-side with the following jQuery (very slightly modified from the link above):

$('#addFileInput').change(function () {
    var file = this.files[0];
    name = file.name;
    size = file.size;
    type = file.type;
    //Your validation
});

$('.submitFile').click(function () {
    var formData = new FormData($("#fileUploadForm"));
    $.ajax({
        url: '/AJAX Pages/Compute_File_Upload.cshtml',  //Server script to process data
        type: 'POST',
        xhr: function () {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) { // Check if upload property exists
                myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: function () {
            $("#progressBar").css("visibility", "visible");
        },
        success: function (response) {
            $(".editLabelTitle").text(response);
        },
        //error: errorHandler,
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});

function progressHandlingFunction(e) {
    if (e.lengthComputable) {
        $('progress').attr({ value: e.loaded, max: e.total });
    }
}

Here's the HTML that is involved:

<div class=\"addFileBox\">
    <div class=\"editPageSubTitle dragHandle\">
        Add File
        <button id=\"closeAddFileBox\">X</button>
    </div>
    <div class=\"innerAddFileDiv\">
        <form id=\"fileUploadForm\" enctype=\"multipart/form-data\">
            <input id=\"addFileInput\" name=\"addFileInput\" type=\"file\" />
        </form>
        <br/>
        <progress id=\"progressBar\"></progress>
        <br/>
        <button class=\"submitFile\">Submit File</button>
    </div>
</div>

The Ajax request in and of itself works fine. The problem comes when I don't know how to get the file on the server-side code (normally I would just find the input with the Request.Files["someFileId"]) but as all formData is sent, this isn't working the way I am familiar with.

C# CODEBEHIND

@{
Layout = "";

if(IsAjax)
{
    var file = Request.Files["addFileInput"];

    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/CMS Files/UtilityBilling"), fileName);
    file.SaveAs(path);
}

}

What is the proper way to access the given file, considering my scenario and environment?

Answer

christiangobo picture christiangobo · Oct 9, 2013

Try this from codebehind:

        HttpFileCollection filesCollection = HttpContext.Current.Request.Files;
        var fileName = filesCollection[0];
        string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/SaveDir"), fileName.FileName);
        fileName.SaveAs(filePath);