【问题标题】:passing information from ASP.NET ashx to aspx将信息从 ASP.NET ashx 传递到 aspx
【发布时间】:2011-10-03 11:25:29
【问题描述】:

我正在使用 Jquery ajax 将文件上传到我的数据库以生成进度条..

问题是,我无法将上传的文件名传递给我的后端代码。我可以很容易地使用 Hiddenfields 和 jquery 传递通过用户发送的文件名,但是如果该文件存在,我的 ASHX 处理程序可能已将其重命名。我尝试使用传递的上下文在 ASHX 文件中创建一个 Session["variable"],但是它为空..

这是我的 Javascript:

$(function () {
    $("#<%=supplierInfo.FUclientID %>").makeAsyncUploader({
        upload_url: '<%=ResolveUrl("~/Controls/UploadHandler.ashx")%>', // Important! This isn't a directory, it's a HANDLER such as an ASP.NET MVC action method, or a PHP file, or a Classic ASP file, or an ASP.NET .ASHX handler. The handler should save the file to disk (or database).
        flash_url: '../../Scripts/swfupload.swf',
        button_image_url: '../../Scripts/blankButton.png',
        disableDuringUpload: 'INPUT[type="submit"]',
        upload_success_handler: function () {
            var hiddenfield = document.getElementById('<% =hdnTest.ClientID %>');
            hiddenfield.value = "test";

            $("span[id$=_completedMessage]", container).html("Uploaded <b>{0}</b> ({1} KB)"
                        .replace("{0}", file.name)
                        .replace("{1}", Math.round(file.size / 1024))
                    );
        }
    });
});

ASHX 处理程序:

<%@ WebHandler Language="C#" Class="UploadHandler" %>

using System;
using System.Web;
using System.IO;

public class UploadHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

        string strFileName = Path.GetFileName(context.Request.Files[0].FileName);
        string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();

        int i = 0;
        while (File.Exists(context.Server.MapPath("~/images/Upload/SupplierImg") + "/" + strFileName))
        {
            strFileName = Path.GetFileNameWithoutExtension(strFileName) + i.ToString() + strExtension;
        }

        string strLocation = context.Server.MapPath("~/images/Upload/SupplierImg") + "/" + strFileName;
        context.Request.Files[0].SaveAs(strLocation);

        context.Response.ContentType = "text/plain";
        context.Response.Write("OK");

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

【问题讨论】:

  • '我试图创建一个 Session["variable"]' - 你的例子中没有。

标签: jquery asp.net ajax


【解决方案1】:

确保在 jQuery AJAX 调用中明确声明内容类型。

$.ajax({
  type: "POST",
  url: "UploadHandler.ashx",
  data: "{ 'fileName' : 'myFileName' }",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data) {
           // This may be data.d depending on what version of .NET you are running
           //     See this link for more info on .d - http://haacked.com/archive/2009/06/25/json-hijacking.aspx

           $("span[id$=_completedMessage]", container).html("Uploaded <b>{0}</b> ({1} KB")
                    .replace("{0}", data.fileName)
                    .replace("{1}", Math.round(data.fileSize / 1024))
           );
  }
});

您可能希望在服务器上预序列化您的数据:

public void ProcessRequest (HttpContext context) {

    string strFileName = Path.GetFileName(context.Request.Files[0].FileName);

...

    context.Response.ContentType = "text/plain";
    context.Response.Write(JsonConvert.SerializeObject(new { fileName = strFileName, fileSize = iFileSize }));

}

【讨论】:

    【解决方案2】:

    为什么不返回strFileName 而不是“OK”,那么你就有了文件名?

    context.Response.Write(strFileName );
    

    【讨论】:

      【解决方案3】:

      如果要在处理程序中使用 Session,则需要实现 IRequiresSessionState 接口。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-26
        • 2014-01-21
        • 2015-07-02
        • 1970-01-01
        • 2017-04-05
        • 1970-01-01
        • 1970-01-01
        • 2014-09-18
        相关资源
        最近更新 更多