最近做一个项目后台发布系统,大致上是使用Jquer插件layer.js、Jquery与一般处理程序实现参数传递数据库及页面交互
下面是使用jquery.form.js插件给一般处理程序传递参数,实现文件上传代码
前台
<tr id="trfileup" style="display: none">
<td align="right">上传文件</td>
<td>
<%--<asp:DropDownList ID="DropDownList2" runat="server" class="select_a" Width="100px">
<asp:ListItem Value=""></asp:ListItem>
<asp:ListItem Value="0"> 路检超标</asp:ListItem>
<asp:ListItem Value="1"> 遥感超标</asp:ListItem>
</asp:DropDownList>
<asp:FileUpload ID="FileUpload1" runat="server" class="inpFlie" Width="260px" /></td>--%>
<select id="DropDownList2" name="" class="select_a">
<option value=""></option>
<option value="0">路检超标</option>
<option value="1">遥感超标</option>
</select>
<input id="fileup" type="file" name="file" size="38" class="inpFlie" />
<%--<img src="images/icon_no.png">--%>
</td>
</tr>
<tr>
<td align="right" valign="top"><span class="c-red">*</span>文章内容</td>
<td>
$("#form1").ajaxSubmit({
data: { "type": $("#DropDownList2").val() },
success: function (str) {
if (str != null && str != "undefined") {
if (str == "1") {
layer.alert("上传成功!", 9);
$("#bbstitle").val("");
$("#select").val("");
$("#DropDownList2").val("");
$("#fileup").val("");
ue.setContent("");
}
else if (str == "2") { layer.alert("上传文件类型错误!", 9); }
else if (str == "3") { layer.alert("文件不能大于1M", 9); }
else if (str == "4") { layer.alert("请选择要上传的公告文件", 9); }
else if (str == "5") { layer.alert("请选择要上传的公告文件类型", 9); }
else { layer.alert('操作失败!', 9); }
}
else layer.alert('操作失败!', 9);
},
error: function (error) { layer.alert(error, 9); },
url: '../Handler/UploadFile.ashx', /*设置post提交到的页面*/
type: "post", /*设置表单以post方法提交*/
dataType: "text" /*设置返回值类型为文本*/
});
后台
/// <summary>
/// UploadFile 的摘要说明
/// </summary>
public class UploadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/text";//ContentType设置成text,方便前台接收参数,判断
HttpServerUtility server = context.Server;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
HttpPostedFile file = context.Request.Files["file"];//注意索引越界?这里file指前台name='file'的input
if (file == null)
{
ResponseWriteEnd(context, "4");//4请选择要上传的文件
}
else
{
string fileName = file.FileName;/*获取文件名: C:\Documents and Settings\Administrator\桌面\123.jpg*/
int a = fileName.LastIndexOf("\\") + 1;
int b = fileName.Length - a;
string fileName1 = fileName.Substring(a, b);
string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();/*获取后缀名并转为小写: jpg*/
string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//发布时间
string filePath = "../Upload/" + fileName1;//文件路径,用于a标签链接下载
string type = request["type"];//公告类型 0路检超标 1遥感超标
string sql = "insert into CBCX(filename,fileurl,time,type) values('" + fileName1 + "','" + filePath + "','" + time + "'," + type + ")";
DBUtility.DataBase.ExecuteSql(sql);//DBUtility是封装的数据库操作类库
int bytes = file.ContentLength;//获取文件的字节大小
string filter = ".xls|.xlsx"; //允许上传的格式
if (!filter.Contains(suffix))
ResponseWriteEnd(context, "2"); //只能允许的文件格式
if (bytes > 1024 * 1024)
ResponseWriteEnd(context, "3"); //文件不能大于1M
file.SaveAs(HttpContext.Current.Server.MapPath(filePath));//保存图片文件到指定路径
ResponseWriteEnd(context, "1"); //上传成功
}
#region 没用的代码,已注释
//if (file.ContentLength>0)
//{
// string extName = Path.GetExtension(file.FileName);
// string fileName = Guid.NewGuid().ToString();
// string fullName = fileName + extName;
// string Filter = ".xls|.xlsx";
// if (Filter.Contains(extName.ToLower()))
// {
// string phyFilePath = server.MapPath("../Upload/") + fullName;
// file.SaveAs(phyFilePath);
// response.Write("{\"State\":\"y\",\"Info\":\"发布成功!\",\"Data\":null}");
// response.Flush();
// }
// else
// {
// response.Write("{\"State\":\"n\",\"Info\":\"文件格式不正确!\",\"Data\":null}");
// }
//}
//else
//{
//}
//System.Web.HttpFileCollection _file = context.Request.Files;//System.Web.HttpContext.Current.Request.Files;
//if (_file.Count>0)
//{
// //文件大小
// long size = _file[0].ContentLength;
// //文件类型
// string type = _file[0].ContentType;
// //文件名
// string name = _file[0].FileName;
// //文件格式
// string _tp = System.IO.Path.GetExtension(name);
// if (_tp.ToLower()==".xlsx"||_tp.ToLower()==".xls")
// {
// //获取文件流
// System.IO.Stream stream = _file[0].InputStream;
// //保存文件
// _file[0].SaveAs("../Upload/" + name);
// }
//}
#endregion
}
private void ResponseWriteEnd(HttpContext context, string msg)
{
context.Response.Write(msg);
context.Response.End();
}
在做文件上传功能的过程中走了许多弯路,以至于卡在某个小的知识点上一天,都怪自己一根筋,幸运的是,背后有高人愿意指点
下面是自己走过的弯路,记录一下
<form id="form1" runat="server" method="post" enctype="multipart/form-data" action="../Handler/UploadFile.ashx">
以为在form表单加上enctype="multipart/form-data"属性就可以直接给post方法一个url后台就能用System.Web.HttpFileCollection _file = System.Web.HttpContext.Current.Request.Files接收了,结果_file为空,一切都扯淡
后来在form表单加了一个action直接指向一般处理程序,这下得到了_file,但是上传完毕后页面会停在指向的一般处理程序(浏览器地址栏url),可以用response.redirect跳转到上传页面,但是无法交互,即无法layer.alert(a,b,c)告诉用户上传成功或者失败,所以只好放弃
更好笑的是以为可以在同一个页面,即使用jquery与一般处理程序又可以用.cs后台代码处理服务器控件,或者是我不懂,或者是实现不了吧