簡體   English   中英

通過jQuery AJAX上傳文件后,HttpPostedFile.ContentLength始終為-2

[英]HttpPostedFile.ContentLength is always -2 after uploading files through jQuery AJAX

我有jQuery AJAX和ASHX行為的奇怪問題。 這是我的代碼:

<input type="file"  ID="FileUpload1"  multiple="multiple" />
<input type="button" ID="Button1"  Text="Upload Selected File(s)" />
function Upload() {
    var data = new FormData();
    jQuery.each($('#FileUpload1')[0].files, function (i, file) {
        data.append('file-' + i, file);
    });

    $.ajax({
        url: "/basic/fileupload/FileUploadHandler.ashx",
        type: "POST",
        contentType: false,
        processData: false,
        cache: false,
        async: true,
        data: data,
        error: function (data) {
            alert("Erro no envio de fotos do projecto. " + data.status);
        }
    });
}
public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    try
    {
        string dirFullPath = HttpContext.Current.Server.MapPath("~/MediaUploader/");
        string[] files;
        int numFiles;
        files = System.IO.Directory.GetFiles(dirFullPath);
        numFiles = files.Length;
        numFiles = numFiles + 1;
        string str_image = "";

        foreach (string s in context.Request.Files)
        {
            HttpPostedFile file = context.Request.Files[s];
            string fileName = file.FileName;
            string fileExtension = file.ContentType;

            if (!string.IsNullOrEmpty(fileName))
            {
                fileExtension = System.IO.Path.GetExtension(fileName);
                str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
                string pathToSave_100 = HttpContext.Current.Server.MapPath("~/files/") + str_image;
                file.SaveAs(pathToSave_100);
            }
        }
        //  database record update logic here  ()

        context.Response.Write(str_image);
    }
    catch (Exception ac)
    {
    }
}

Eeverything似乎很好,但結果是:

context.Request.Files[0]
{System.Web.HttpPostedFile}
    ContentLength: -2
    ContentType: "image/png"
    FileName: "icon-large.png"
    InputStream: {System.Web.HttpInputStream}

我可以接收文件名,但ContentLength總是-2 ,保存文件后只有0字節是大小。 你能幫我解決這個問題嗎?

更新: 我發現了一些新東西,它與ASP.net開發服務器(通過在Visual Studio中推送F5 Key直接運行應用程序)一起正常工作但是IIS 8.5配置有問題

另外我的web.config請求長度參數是:

    <httpRuntime requestValidationMode="2.0" maxRequestLength="10240000" requestLengthDiskThreshold="10240000" />

更新2: 將應用程序池更改為托管管道模式到Classic將解決問題,但我將丟失我的URL重寫,因此我無法更改我的管道模式。 任何想法?

我找到了解決這個問題的解決方案。 我不知道是不是很好但是解決了我的情況:

我用了

void Application_BeginRequest(object sender, EventArgs e) 

Global.asax中

文件來管理請求,因為內容在那里正確可見。 還有其他想法嗎?

暫無
暫無

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

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