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

2019-12-26 18:41:04于海丽
易采站长站为您分析C#简单实现文件上传功能,利用MVC+EF+LigerUI 实现的upload上传功能,感兴趣的小伙伴们可以参考一下  

最近项目上的一个上传文件功能,项目是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.HashPass