C#簡略完成文件上傳功效。本站提示廣大學習愛好者:(C#簡略完成文件上傳功效)文章只能為提供參考,不一定能成為您想要的結果。以下是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.WordStr("'", "\"");
context.Response.Write(r);
context.Response.End();
}
}
public bool IsReusable {
get {
return false;
}
}
}
}
頁眼前台處置以下圖:

#FilesUrl 是一個文本框,將上傳文件的途徑賦值出來,將地址存入數據庫,後續直接依據地址可以下載檢查。
以上就是完成C#文件上傳功效的簡略三步,願望對年夜家的進修有所贊助。