将信息从ASP.NET ashx传递给aspx

时间:2011-10-02 20:57:40

标签: jquery asp.net ajax

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

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

这是我的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;
        }
    }

}

3 个答案:

答案 0 :(得分:0)

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

context.Response.Write(strFileName );

答案 1 :(得分:0)

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

答案 2 :(得分:0)

确保在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 }));

}