700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > ashx 获取上传的文件_asp.net利用ashx文件实现文件的上传功能

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

时间:2021-11-23 12:05:42

相关推荐

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;

}

}

}

}

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。