C# · 12月 30, 2021

C#简单实现文件上传功能

最近项目上的一个上传文件功能,项目是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#文件上传功能的简单三步,希望对大家的学习有所帮助。