最近项目上的一个上传文件功能,项目是MVC+EF+ligerUI 来做的,贴出来大家一起分享下
1、页面需要引用这个Js 和 CSS
<script type="text/JavaScript" src="/Content/uploadify/jquery.uploadify.min.Js"></script>
<link href="/Content/uploadify/uploadify.CSS" type="text/CSS" rel="stylesheet" />
2、页面添加Upload.ashx
3、代码如下:
using System;using System.Collections.Generic;using System.linq;using System.Web;using System.IO;using System.Web.Security;namespace AL.Web { /// <summary> /// Upload 的摘要说明 /// </summary> public class Upload : IhttpHandler { public voID ProcessRequest(httpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string r = ""; //此处有时候穿过来的sn后面还有一些乱七八糟的字符,没研究什么意思,就判断一下,截取一下就完事了,小项目~ string sn = context.Request.queryString["sn"]; if (sn != null && sn.Length > 14) sn = sn.Substring(0,14); if (context.User.IDentity.IsAuthenticated == false) { // 未登录用户 } try { //获取上传的文件数据 httpPostedfile file = context.Request.files["filedata"]; string filename = file.filename; string fileType = Path.GetExtension(filename).Tolower(); //由于不同浏览器取出的filename不同(有的是文件绝对路径,有的是只有文件名),故要进行处理 if (filename.IndexOf(' ') > -1) { filename = filename.Substring(filename.LastIndexOf(' ') + 1); } else if (filename.IndexOf('/') > -1) { filename = filename.Substring(filename.LastIndexOf('/') + 1); } //上传的目录 string uploadDir = "~/Content/uploadfile/TMP/" + System.DateTime.Now.ToString("yyyyMM") + "/"; //上传的路径 //生成年月文件夹及日文件夹 if (Directory.Exists(context.Server.MapPath(uploadDir)) == false) { Directory.CreateDirectory(context.Server.MapPath(uploadDir)); } if (Directory.Exists(context.Server.MapPath(uploadDir + System.DateTime.Now.ToString("dd") + "/")) == false) { Directory.CreateDirectory(context.Server.MapPath(uploadDir + System.DateTime.Now.ToString("dd") + "/")); } uploadDir = uploadDir + System.DateTime.Now.ToString("dd") + "/"; string uploadpath = uploadDir + FormsAuthentication.HashPasswordForStoringInConfigfile(filename,"MD5").Substring(0,8) + fileType; //保存文件 file.SaveAs(context.Server.MapPath(uploadpath)); //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失 //DbHelperoleDb.Executesql("insert into [temp](temp_sn,temp_Content) values('" + sn + "','" + uploadpath + "')"); //Response.Write("1"); //context.Response.Write("{'IsError':false,'Data':'" + uploadpath + "'}"); r = "{'IsError':false,'Data':'" + uploadpath + "'}"; } catch (Exception ex) { //Response.Write("0"); //throw ex; //context.Response.Write("{IsError: true,data:'" + ex.Message + "'}"); r = "{'IsError':true,'Data':'" + ex.Message + "'}"; } finally { r = r.Replace("'","\""); context.Response.Write(r); context.Response.End(); } } public bool IsReusable { get { return false; } } }}
页面前台处理如下图:
#filesUrl 是一个文本框,将上传文件的路径赋值进去,将地址存入数据库,后续直接根据地址可以下载查看。
以上就是实现C#文件上传功能的简单三步,希望对大家的学习有所帮助。
总结以上是内存溢出为你收集整理的C#简单实现文件上传功能全部内容,希望文章能够帮你解决C#简单实现文件上传功能所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)