簡體   English   中英

如何從asp.net-webpages中的Ajax請求獲取服務器端的發布文件?

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

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

如何異步上傳文件?

我能夠使用以下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"])的輸入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);
}

}

考慮到我的場景和環境,訪問給定文件的正確方法是什么?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM