前言:
今天大家对“ajax调用ashx方法”大致比较关切,兄弟们都想要知道一些“ajax调用ashx方法”的相关内容。那么小编在网上汇集了一些有关“ajax调用ashx方法””的相关文章,希望你们能喜欢,姐妹们一起来了解一下吧!一、数据库设计
二、Model实体类
public class banqi_attach { public int id { get; set; } public string bqid { get; set; } public string file_name { get; set; } public string file_path { get; set; } public int file_size { get; set; } public DateTime create_time { get; set; } public DateTime update_time { get; set; } }
三、DAL数据访问层:注意涉及增加和根据id获取列表用于显示
//增加数据 public int Add(Model.banqi_attach model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into banqi_attach("); strSql.Append("[bqid],[file_name] ,[file_path] ,[file_size],[create_time] )"); strSql.Append(" values ("); strSql.Append("@bqid,@file_name,@file_path,@file_size,@create_time)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@bqid", SqlDbType.NVarChar,20), new SqlParameter("@file_name", SqlDbType.NVarChar,50), new SqlParameter("@file_path", SqlDbType.NVarChar,100), new SqlParameter("@file_size", SqlDbType.Int), new SqlParameter("@create_time", SqlDbType.DateTime) }; parameters[0].Value = model.bqid; parameters[1].Value = model.file_name; parameters[2].Value = model.file_path; parameters[3].Value = model.file_size; parameters[4].Value = model.create_time; //添加主表数据 object obj = new SqlHelper().ExecuteScalar(strSql.ToString(), parameters, CommandType.Text); model.id = Convert.ToInt32(obj); return model.id; } //根据bqid 显示附件列表 public DataTable GetList(string bqid) { StringBuilder strSql = new StringBuilder(); strSql.Append("select * from banqi_attach where bqid='"+bqid+"'"); return new SqlHelper().ExecuteQuery(strSql.ToString(), CommandType.Text); }
四、前台页面:包含一些对上传文件基本属性的验证,如类型、大小等
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="banqi_attach.aspx.cs" Inherits="Peixun.Web.banqi_attach" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ";><html xmlns=";><head runat="server"> <title>班期附件</title> <style type="text/css"> *{margin:0;padding:0;}a{text-decoration:none;}ul.imglist{ margin:0 auto; overflow:hidden;}ul.imglist li{list-style:none; float:left; padding:14px 8px; width:280px; margin-bottom:20px; }ul.imglist li img{ display:block; width:280px; height:200px}ul.imglist li span{ display:block;width:100%; height:30px; line-height:30px; background:#F6F6F6;text-align:center;text-decoration: none;}.part{ margin:0 auto; width:1200px;}</style><link rel="stylesheet" href="./css/xadmin.css"> <script src="; type="text/javascript"> </script> <script src="js/ajaxfileupload.js" type="text/javascript"></script></head><body><div class="part"> <form id="form1" runat="server"> 附件名称:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /> <div class="layui-upload"> <asp:FileUpload ID="FileUpload" runat="server" /> <input type="button" value="上传图片 " class="layui-btn layui-btn-danger" onclick="ajaxFileUpload()"/> <br /><br /> <div style="border: 1px solid blue;"> <img alt="" class="layui-upload-img" id="demo1" style=" width:300px; height:200px;"> <asp:Label ID="demoText" runat="server"></asp:Label> <asp:HiddenField ID="HiddenField1" runat="server" /> <asp:HiddenField ID="HiddenField2" runat="server" /> </div> </div> <asp:Button ID="btnSubmit" runat="server" Text="确定上传" CssClass="layui-btn" onclick="btnSubmit_Click" /></div><!--图片列表--> <asp:Repeater ID="rptList2" runat="server"> <HeaderTemplate><div class="part"> <h3>附件列表</h3><ul class="imglist"> </HeaderTemplate> <ItemTemplate> <li> <a href="<%#Eval("file_path")%>" target="_blank"> <img src=<%#Eval("file_path")%> /> <span><%#Eval("file_name")%><br /><%#Eval("create_time")%></span> </a> </li> </ItemTemplate> <FooterTemplate> <%#rptList2.Items.Count == 0 ? "<div align=\"center\" style=\"font-size:12px;line-height:30px;color:#666;\">暂无记录</div>" : ""%> </ul> </div> </FooterTemplate> </asp:Repeater> <!--/图片列表--></div> </form><script type="text/javascript"> function ajaxFileUpload() { var filePath = $("#FileUpload").val(); if (filePath == "") { alert("请选择文件"); } var size = $("#FileUpload")[0].files[0].size; //获取文件大小,单位字节B alert(size); var type = filePath.substr(filePath.indexOf(".")); //获取扩展名,格式如.jpg if (type == ".jpg" || type == ".gif" || type == ".JPG" || type == ".GIF") { alert("符合要求格式"); } else { alert("格式错误"); } $.ajaxFileUpload( { url: 'ajaxupload.ashx', //需要链接到服务器地址 secureuri: false, fileElementId: 'FileUpload', //文件选择框的id属性 dataType: 'json', //服务器返回的格式,可以是json success: function (data, status) //相当于java中try语句块的用法 { $("#demo1").attr("src", "../upload/" + data.savefilename + ""); $("#demoText").html(data.msg); $("#HiddenField1").val("/upload/" + data.savefilename); $("#HiddenField2").val(data.filesize); }, error: function (data, status, e) //相当于java中catch语句块的用法 { alert(data.error); } } ); }</script></body></html>
五、异步处理ashx文件
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Peixun.Web{ /// <summary> /// ajaxupload 的摘要说明 /// </summary> public class ajaxupload : IHttpHandler { public void ProcessRequest(HttpContext context) { string msg = string.Empty; string error = string.Empty; string result = string.Empty; HttpPostedFile _upfile = context.Request.Files["FileUpload"]; string savepath = HttpContext.Current.Server.MapPath("~") + "\\upload\\"; int file_size = _upfile.ContentLength; //获取上传文件大小 //判断上传文件夹是否存在,若不存在,则创建 if (!System.IO.Directory.Exists(savepath)) { System.IO.Directory.CreateDirectory(savepath); //创建文件夹 } if (_upfile.FileName != "") { //string savefilename = System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_" + _upfile.FileName;//声称文件名,以时间命名防止重复 string savefilename = System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + _upfile.FileName.Substring(_upfile.FileName.IndexOf(".")).ToLower(); //注意Substring和IndexOf的写法中的大小写,获取扩展名并小写。 _upfile.SaveAs(savepath + savefilename); msg = "文件上传成功!"; result = "{msg:'" + msg + "',savefilename:'" + savefilename + "',filesize:'"+file_size.ToString()+"'}"; } else { error = "文件上传失败!"; result = "{ error:'" + error + "'}"; } context.Response.Write(result); context.Response.End(); } public bool IsReusable { get { return false; } } }}
六、页面后台代码
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Data.SqlClient;namespace Peixun.Web{ public partial class banqi_attach : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataTable dt = new DAL.banqi_attach().GetList( Request.QueryString["bqid"]); rptList2.DataSource = dt; rptList2.DataBind(); } #region 增加操作================================= private bool DoAdd() { bool result = false; Model.banqi_attach model = new Model.banqi_attach(); model.file_name = TextBox1.Text.Trim(); model.file_path = HiddenField1.Value; model.create_time = DateTime.Now; model.bqid = Request.QueryString["bqid"]; model.file_size =Convert.ToInt32(HiddenField2.Value); if (new DAL.banqi_attach().Add(model) > 0) { result = true; } return result; } #endregion //保存 protected void btnSubmit_Click(object sender, EventArgs e) { if (!DoAdd()) { Response.Write("<script>alert('错误!');</script>"); return; } else { Response.Write("<script>alert('上传成功!');var index = parent.layer.getFrameIndex(window.name);parent.layer.close(index); parent.location.reload(); </script>"); } } }}
七、效果图
版权声明:
本站文章均来自互联网搜集,如有侵犯您的权益,请联系我们删除,谢谢。
标签: #ajax调用ashx方法