ashx 获取上传的文件_HTML C# ajax结合ashx处理程序实现文件上传

ajax结合ashx处理程序实现文件上传

一、ajaxFileUpload是一个异步上传文件的jQuery插件。

ajaxFileUpload参数说明:(copy了别人的参数说明)

1、url            上传处理程序地址。

2,fileElementId       需要上传的文件域的ID,即的ID。

3,secureuri        是否启用安全提交,默认为false。

4,dataType        服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。

5,success        提交成功后自动执行的处理函数,参数data就是服务器返回的数据。

6,error          提交失败自动执行的处理函数。

7,data          自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。

8, type           当要提交自定义参数时,这个参数要设置成post

HTML代码:

1

2

3

4

5

6

7

8

9

10

11

12 .file {13 position: relative;14 background-color: #b32b1b;15 border: 1px solid #ddd;16 width: 68px;17 height: 25px;18 display: inline-block;19 text-decoration: none;20 text-indent: 0;21 line-height: 25px;22 font-size: 14px;23 color: #fff;24 margin: 0auto;25 cursor: pointer;26 text-align: center;27 border: none;28 border-radius: 3px;29 }30

31 .file input {32 position: absolute;33 top: 0;34 left: -2px;35 opacity: 0;36 width: 10px;37 }38

39

40 $(function () {41 //选择文件

42 $(".file").on("change", "input[type=‘file‘]", function () {43 var filePath = $(this).val();44 //设置上传文件类型

45 if (filePath.indexOf("xls") != -1 || filePath.indexOf("xlsx") != -1) {

46

47 //上传文件

48 $.ajaxFileUpload({49 url: ‘FileHandler.ashx‘,//处理程序路径

50 secureuri: false,51 fileElementId: ‘btnfile‘,52 dataType: ‘json‘,53 success: function (data, status) {54 //获取上传文件路径55 //$("#txt_filePath").val(data.filenewname);

56 alert("文件上传成功!");57 },58 error: function (data, status, e) {59 //alert(e);

60 alert("not");61 }62 });63

64

65 } else {66 alert("请选择正确的文件格式!");67 //清空上传路径68 $("#txt_filePath").val("");69 return false;70 }

71 });72 })73

74

75

76

77

78

79

80 选择文件:

81 浏览

82

83

84

ashx代码:

1

2

3 usingSystem;4 usingSystem.Web;5

6 public classFileHandler : IHttpHandler {7

8 public voidProcessRequest (HttpContext context) {9 //context.Response.ContentType = "text/plain";10 //context.Response.Write("Hello World");

11

12

13 context.Response.ContentType = "text/plain";14 string msg = string.Empty;15 string error = string.Empty;16 string result = string.Empty;17 string filePath = string.Empty;18 string fileNewName = string.Empty;19

20 //这里只能用才能有效果,因为服务器控件是HttpInputFile类型

21 HttpFileCollection files =context.Request.Files;22 if (files.Count > 0)23 {24 //设置文件名

25 fileNewName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + System.IO.Path.GetFileName(files[0].FileName);26 //保存文件

27 files[0].SaveAs(context.Server.MapPath("~/Upload/" +fileNewName));28 msg = "文件上传成功!";29 result = "{msg:‘" + msg + "‘,filenewname:‘" + fileNewName + "‘}";30 }31 else

32 {33 error = "文件上传失败!";34 result = "{ error:‘" + error + "‘}";35 }36 context.Response.Write(result);37 context.Response.End();38 }39

40 public boolIsReusable {41 get{42 return false;43 }44 }45

46 }

如果想上传多张图片只要给  input 添加一个 multiple 属性

即:

就可以上传多个图片

ajaxFileUpload下载:

链接:https://pan.baidu.com/s/1slkfpOp 密码:5s8r

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我理解你的要求。以下是一个简单的示例,用ajax实现增删改查前后端,使用html文件、js文件中应用ajax为前端,一般处理程序ashx为后端,使用SqlServer数据库: 前端HTML文件: ```html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <title>使用ajax实现增删改查</title> </head> <body> <h1>使用ajax实现增删改查</h1> <h2>增加数据</h2> <input type="text" id="name" placeholder="姓名"> <input type="text" id="age" placeholder="年龄"> <button onclick="add()">确定</button> <h2>修改数据</h2> <input type="text" id="id" placeholder="id"> <input type="text" id="newName" placeholder="新姓名"> <input type="text" id="newAge" placeholder="新年龄"> <button onclick="update()">确定</button> <h2>删除数据</h2> <input type="text" id="delId" placeholder="要删除的id"> <button onclick="del()">确定</button> <h2>查找数据</h2> <input type="text" id="findId" placeholder="要查找的id"> <button onclick="find()">确定</button> <h2>所有数据</h2> <button onclick="findAll()">确定</button> <div id="result"></div> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script src="script.js"></script> </body> </html> ``` 前端JS文件: ```js function add() { var name = $("#name").val(); var age = parseInt($("#age").val()); $.ajax({ url: "handler.ashx", type: "POST", data: { method: "add", name: name, age: age }, success: function(result) { $("#result").html(result); } }); } function update() { var id = parseInt($("#id").val()); var name = $("#newName").val(); var age = parseInt($("#newAge").val()); $.ajax({ url: "handler.ashx", type: "POST", data: { method: "update", id: id, name: name, age: age }, success: function(result) { $("#result").html(result); } }); } function del() { var id = parseInt($("#delId").val()); $.ajax({ url: "handler.ashx", type: "POST", data: { method: "del", id: id }, success: function(result) { $("#result").html(result); } }); } function find() { var id = parseInt($("#findId").val()); $.ajax({ url: "handler.ashx", type: "POST", data: { method: "find", id: id }, success: function(result) { $("#result").html(result); } }); } function findAll() { $.ajax({ url: "handler.ashx", type: "POST", data: { method: "findAll" }, success: function(result) { $("#result").html(result); } }); } ``` 后端处理程序ashx文件: ```cs <%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Data.SqlClient; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; string method = context.Request.Form["method"]; if (method == "add") { string name = context.Request.Form["name"]; int age = Convert.ToInt32(context.Request.Form["age"]); Add(name, age); context.Response.Write("增加成功"); } else if (method == "update") { int id = Convert.ToInt32(context.Request.Form["id"]); string name = context.Request.Form["name"]; int age = Convert.ToInt32(context.Request.Form["age"]); Update(id, name, age); context.Response.Write("修改成功"); } else if (method == "del") { int id = Convert.ToInt32(context.Request.Form["id"]); Del(id); context.Response.Write("删除成功"); } else if (method == "find") { int id = Convert.ToInt32(context.Request.Form["id"]); string result = Find(id); context.Response.Write(result); } else if (method == "findAll") { string result = FindAll(); context.Response.Write(result); } else { context.Response.Write("输入错误的方法"); } } public bool IsReusable { get { return false; } } private void Add(string name, int age) { string connectionString = "Server=(localdb)\\mssqllocaldb;Database=mydatabase;Trusted_Connection=True;"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand("INSERT INTO mytable(name, age) VALUES(@name, @age)", connection); command.Parameters.AddWithValue("@name", name); command.Parameters.AddWithValue("@age", age); command.ExecuteNonQuery(); } } private void Update(int id, string name, int age) { string connectionString = "Server=(localdb)\\mssqllocaldb;Database=mydatabase;Trusted_Connection=True;"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand("UPDATE mytable SET name=@name, age=@age WHERE id=@id", connection); command.Parameters.AddWithValue("@id", id); command.Parameters.AddWithValue("@name", name); command.Parameters.AddWithValue("@age", age); command.ExecuteNonQuery(); } } private void Del(int id) { string connectionString = "Server=(localdb)\\mssqllocaldb;Database=mydatabase;Trusted_Connection=True;"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand("DELETE FROM mytable WHERE id=@id", connection); command.Parameters.AddWithValue("@id", id); command.ExecuteNonQuery(); } } private string Find(int id) { string connectionString = "Server=(localdb)\\mssqllocaldb;Database=mydatabase;Trusted_Connection=True;"; string result = ""; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand("SELECT * FROM mytable WHERE id=@id", connection); command.Parameters.AddWithValue("@id", id); SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { string name = reader["name"].ToString(); int age = Convert.ToInt32(reader["age"]); result = String.Format("姓名:{0} 年龄:{1}", name, age); } } return result; } private string FindAll() { string connectionString = "Server=(localdb)\\mssqllocaldb;Database=mydatabase;Trusted_Connection=True;"; string result = ""; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand("SELECT * FROM mytable", connection); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { int id = Convert.ToInt32(reader["id"]); string name = reader["name"].ToString(); int age = Convert.ToInt32(reader["age"]); result += String.Format("id:{0} 姓名:{1} 年龄:{2}<br>", id, name, age); } } return result; } } ``` 你可以在SqlServer数据库中创建一个名为mydatabase的数据库,并在其中创建一个名为mytable的表,包含id(int),name(varchar),age(int)三个字段。 希望这个示例对你有所帮助。如果有任何问题或需要进一步帮助,请随时问我。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值