c#通用处理程序不能从post中获取数据

本文关键字:post 获取 数据 不能 处理 程序 | 更新日期: 2023-09-27 18:15:47

我正在做一个简单的c#通用处理程序,应该接收表单帖子。这是表格…

<form id="frmUploadImage" action="../Handlers/LocalImageUploadHandler.ashx" method="post" style="display: none">
    <div>
        <input style="display: none; margin-bottom: 20px" type="file" id="uploadImage" />
    </div>
</form>

我有一些代码,在单击按钮时调用输入的单击事件。当输入被加载时,下面的代码被调用(我可以设置一个断点,它会到达这里)。

var jqxhr = $.post('../Handlers/LocalImageUploadHandler.ashx', $('#frmUploadImage').serialize())
            .success(function() {
                alert('worked');
            })
            .error(function() {
                alert('failed');
            });

它将显示"失败"的警告。在服务器端,它在处理程序中调用这个(我可以通过设置断点来验证它是否被调用)。

public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/octet-stream";
        var file = Convert.FromBase64String(context.Request.Form["uploadedFile"]);
//other stuff
}
有趣的是context.Request.Form和context.Request.Files属性中没有项,即使它们正在被发送。我所做的一切都不起作用。我试过用XHR, jQuery等发布。我尝试过将数据作为DataUrl从文件上传控件中取出,并将其序列化为base64编码的字符串,然后将其放入ajax调用中。处理程序将接收到一个post,但是数据正在被剥离。

c#通用处理程序不能从post中获取数据

您需要尝试以下代码以使其工作用户端代码$ (" # btnUpload")。点击(function () {

var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
var test = new FormData();
for (var i = 0; i < files.length; i++) {
test.append(files[i].name, files[i]);
}
$.ajax({
url: "LocalImageUploadHandler.ashx",
type: "POST",
contentType: false,
processData: false,
data: test,
// dataType: "json",
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
});

服务器端代码

public void ProcessRequest (HttpContext context) {
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fname;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '''' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
fname=Path.Combine(context.Server.MapPath("~/uploads/"), fname);
file.SaveAs(fname);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File Uploaded Successfully!");
}
public bool IsReusable {
get {
return false;
}
}