3

使用我在这里找到的有用信息:

如何异步上传文件?

我能够使用以下 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"])

C# 代码隐藏

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

}

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

4

1 回答 1

2

从代码隐藏试试这个:

        HttpFileCollection filesCollection = HttpContext.Current.Request.Files;
        var fileName = filesCollection[0];
        string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/SaveDir"), fileName.FileName);
        fileName.SaveAs(filePath);
于 2013-10-09T19:34:36.703 回答