如何从asp.net-webpages中的Ajax请求获取服务器端的发布文件?

时间:2013-10-09 19:04:34

标签: c# jquery ajax webmatrix asp.net-webpages

使用我在此处找到的有用信息:

How can I upload files asynchronously?

我能够使用以下jQuery将表单数据传送到服务器端(从上面的链接稍微修改一下):

$('#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 });
    }
}

以下是涉及的HTML:

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

Ajax请求本身就可以正常工作。当我不知道如何在服务器端代码上获取文件时出现问题(通常我会找到带有Request.Files["someFileId"])的输入,但是因为所有的formData都被发送了,所以这不是我的工作方式我很熟悉。

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

}

考虑到我的场景和环境,访问给定文件的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

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