ashx 获取上传的文件_asp.net利用ashx文件实现文件的上传功能

原来以为文件上传是一个比较简单的功能,结果搞了一个晚上才搞定~这里主要介绍两种方法实现。

方法一:Form表单提交

html代码:

上传文件

UploadHandler.ashx代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace WebApplication1

{

///

/// UploadHandler 的摘要说明

///

public class UploadHandler : IHttpHandler

{

public void ProcessRequest(HttpContext context)

{

context.Response.ContentType = "text/plain";

HttpPostedFile file = context.Request.Files["file_upload"];

string filePath = context.Server.MapPath("~/UploadFiles/") + System.IO.Path.GetFileName(file.FileName);

file.SaveAs(filePath);

context.Response.Write("上传文件成功");

}

public bool IsReusable

{

get

{

return false;

}

}

}

}

该方法虽然能够实现文件的上传,但是form表单提交之后整个页面就刷新了,如果要无刷新上传文件的话,就要使用ajax了。

方法二:jquery + ajax无刷上传

html代码:

上传文件

$(document).ready(function ()

{

$('#btn_upload').bind('click', function ()

{

var formData = new FormData();

formData.append('upload_file', $('#file_upload')[0].files[0]);

$.ajax({

url: 'UploadHandler.ashx',

type: 'post',

data: formData,

contentType: false,

processData: false,

success: function (msg)

{

if (msg == "Yes")

{

alert('文件上传成功');

}

else

{

alert('文件上传失败');

}

}

})

});

});

UploadHandler.ashx代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace WebApplication1

{

///

/// UploadHandler 的摘要说明

///

public class UploadHandler : IHttpHandler

{

public void ProcessRequest(HttpContext context)

{

context.Response.ContentType = "text/plain";

if (context.Request.Files.Count > 0)

{

HttpPostedFile file = context.Request.Files["upload_file"];

string filePath = context.Server.MapPath("~/UploadFiles/") + System.IO.Path.GetFileName(file.FileName);

file.SaveAs(filePath);

context.Response.Write("Yes");

}

else

{

context.Response.Write("No");

}

}

public bool IsReusable

{

get

{

return false;

}

}

}

}

个人更推荐方法二,运行结果如下图所示:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值