读书人

asp.net中的ashx页无法读取上传的文件

发布时间: 2012-05-01 12:48:58 作者: rapoo

asp.net中的ashx页无法读取上传的文件
a.ascx页面通过Jquery的Ajax异步上传文件,转到b.ashx页处理。所有参数都能a.ashx页获取,但就是无法读取到文件。

a.ascx的相关代码如下:

C# code
function PostImage() {            $.post("../../../AjaxResponse/Handler.ashx?time=" + Math.random(), {            imgPath: $("#imgFileUpload").val(),            action: "checkSize",            filepath: "temp",            maxSize: "5000"         },                          function (data) {                                                                $("#imgPreview").attr("src", data.toString()); //显示缩略图                                                       });    }


b.ashx页面的相关代码如下:
C# code
public class TypeEditCoverHandler : IHttpHandler{         //获取栏目类别的封面图片    public void ProcessRequest(HttpContext context)    {        //context.Request.ContentType = "multipart/form-data";        context.Response.ContentType = "text/plain";                //获取页面传过来的状态        string strState = context.Request["action"];        //获取文件大小限制        int maxSize = Moore.Help.DataConverter.StrToInt(context.Request["maxSize"]);        //获取文件路径        string strImgPath = context.Request["imgPath"]; //能正确读到:D:\图片上传测试\04.jpg        HttpPostedFile imgPostFile = context.Request.Files[strImgPath];  //一直为null        //临时文件名称        string strTempImageName = String.Empty;        …… 后面的略


HttpPostedFile imgPostFile这句得到的文件一直为null,请问是什么原因?

[解决办法]
context.Request.Files[0]
[解决办法]
你这种方法是没有办法读取到到file的,可以用jquery form来实现
[解决办法]
必须是post提交,并且form enctype="multipart/form-data"
[解决办法]
jQuery上传文件

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script src="jquery-1.7.1.min.js"></script>
<script src="jquery.form.js"></script>
<script type="text/javascript">
function upload() {
$("#form1").ajaxSubmit({
success: function (str) {
alert(str);
},
error: function (error) { alert(error); },
url: 'handler1.ashx', /*设置post提交到的页面*/
type: "post", /*设置表单以post方法提交*/
dataType: "text" /*设置返回值类型为文本*/
});
}
</script>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" id="file" name="file" />
<asp:Button ID="Button1" runat="server" Text="上传" OnClientClick="upload();return false;" />
</form>
</body>

handler1.ashx

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

using System;
using System.Web;

public class handler1 : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
HttpPostedFile file = context.Request.Files[0];
String fileName = System.IO.Path.GetFileName(file.FileName);
file.SaveAs(context.Server.MapPath("~/") + fileName);
context.Response.Write("OK");
}

public bool IsReusable {


get {
return false;
}
}
}

jquery.form.js下载地址
http://malsup.github.com/jquery.form.js

读书人网 >asp.net

热点推荐