C#——文件上傳(一般處理程序ashx)


Framework版本:.Net Framework 4

1、FileInfo實體

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Bson;
using ReligionServer.util;
using ReligionServer.constant;

namespace ReligionServer.Model
{
    //為什么會有多余的get set方法,因為測試寫的,沒有刪
    //封裝的一個文件類, 文件基本信息
    public class FileInfo
    {

        public ObjectId _id;

        public String FileCode { get; set; }//目前還沒有研究出ObjectId序列化的最好解決方式, 所以暫時使用FileCode替代Id
        public String Name { get; set; }
        public String Type { get; set; }
        public String Desc { get; set; }
        public String Path { get; set; }
        public int Access { get; set; }
        public String ForeignKey { get; set; }
        public DateTime CreateTime { get; set; }
        public String TypeCode { get; set; }//輔助字段

        public FileInfo() { }

        public void set_Id(ObjectId id)
        {
            this._id = id;
        }

        public ObjectId get_Id()
        {
            return this._id;
        }

        public void setFileCode()
        {
            this.FileCode = CommonUtil.CreateId();
        }

        public String getFileCode()
        {
            return this.FileCode;
        }

        public void setName(String name)
        {
            this.Name = name;
        }

        public String getName()
        {
            return this.Name;
        }

        public void setType(String type)
        {
            this.Type = FileTypeConstant.GetType(type);
        }

        public String getType()
        {
            return this.Type;
        }

        public void setDesc(String desc)
        {
            this.Desc = desc;
        }

        public String getDesc()
        {
            return this.Desc;
        }

        public void setPath(String path)
        {
            this.Path = path;
        }

        public String getPath()
        {
            return this.Path;
        }

        public void setAccess(int access)
        {
            this.Access = access;
        }

        public int getAccess()
        {
            return this.Access;
        }

        public void setForeignKey()
        {
            this.ForeignKey = CommonUtil.CreateId();
        }

        public String getForeignKey()
        {
            return this.ForeignKey;
        }

        public void setCreateTime()
        {
            this.CreateTime = DateTime.Now;
        }

        public DateTime getCreateTime()
        {
            return this.CreateTime;

        }

        public void setTypeCode(String code)
        {
            this.TypeCode = code;
        }

        public String getTypeCode()
        {
            return this.TypeCode;
        }

    }
}

2、Handler具體實現

using System;

using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReligionServer.util;
using ReligionServer.Model;
using ReligionServer.service;
using System.Text.RegularExpressions;

namespace ReligionServer.handler
{
    /// <summary>
    /// FileHandler 的摘要說明
    /// 處理文件請求
    /// </summary>
    public class FileHandler : BaseHandler, IHttpHandler
    {

        private FileInfoService fileInfoService = new FileInfoService();
        private readonly String targetSavePath = "~/ReligionFile/";

        public void ProcessRequest(HttpContext context)
        {
            base.InitAction(context);
        }
        #region 文件上傳
        //和第三方表關聯的文件上傳初始化邏輯
        public void Upload_Foreign(HttpContext context)
        {
            Model.FileInfo fileInfo = InitFileInfo(context, 0);
            if (CommonUtil.IsEmpty(fileInfo.getForeignKey()))
            {
                NoParams<Model.FileInfo>(context, "關聯外鍵為空, 還請檢測關聯屬性是否上傳成功, 外鍵是否為空");
            }
            else if (base.IsEmpty(fileInfo.getTypeCode()))
            {
                fileInfo.setTypeCode("0");
                NoParams<Model.FileInfo>(context, "TypeCode is null or  '' ...");
            }
            else
            {
                List<Model.FileInfo> uploadFileList = FileInsert(context, InitFileInfo(context, 0));
                if (uploadFileList.Count == 0)
                {
                    Error<String>(context, new List<String>() { "上傳失敗: 后台獲取文件信息失敗" });
                }
                else
                {
                    int errorCount = (int)context.Items["FileUploadErrorCount"];
                    int successCount = uploadFileList.Count - errorCount;
                    Success<String>(context, new List<String>() { "一共上傳 " + uploadFileList.Count + "個文件,其中成功 " + successCount + "個,失敗" + errorCount + "" });
                }
            }


            
        }

        //文件上傳初始化邏輯
        public void Upload(HttpContext context)
        {
            Model.FileInfo fileInfo = InitFileInfo(context, 1);
            if (base.IsEmpty(fileInfo.getTypeCode()))
            {
                fileInfo.setTypeCode("0");
                NoParams<Model.FileInfo>(context, "TypeCode is null or  '' ...");
            }
            else {
                List<Model.FileInfo> uploadFileList = FileInsert(context, fileInfo);
                if (uploadFileList.Count == 0)
                {
                    Error<String>(context, new List<String>() { "上傳失敗: 后台獲取文件信息失敗" });
                }
                else
                {
                    int errorCount = (int)context.Items["FileUploadErrorCount"];
                    int successCount = uploadFileList.Count - errorCount;
                    Success<String>(context, new List<String>() { "一共上傳 " + uploadFileList.Count + "個文件,其中成功 " + successCount + "個,失敗" + errorCount + "" });
                }
            }
        }

        /// <summary>
        /// 供類相互調用的文件上傳
        /// </summary>
        /// <param name="context"></param>
        /// <param name="foreignKey"></param>
        /// <returns></returns>
        public List<Model.FileInfo> Upload_Invoke(HttpContext context, String foreignKey) {
            if (!base.IsEmpty(foreignKey)) {
                Model.FileInfo fileInfo = InitFileInfo(context, 0);
                fileInfo.ForeignKey = foreignKey;
                List<Model.FileInfo> uploadFileList = FileInsert(context, fileInfo);
                return uploadFileList;
            }
            return new List<Model.FileInfo>();
        }

        //執行文件轉存以及數據庫記錄插入的方法
        private List<Model.FileInfo> FileInsert(HttpContext context, Model.FileInfo fileInfo)
        {
            List<Model.FileInfo> fileInfoList = new List<Model.FileInfo>();

            //List<Model.FileInfo> fileInfoList = new List<Model.FileInfo>();
            String directoryName = DateUtil.CurrentDateTimeValue();//文件夾名稱
            //HttpContext.Current.Request.PhysicalApplicationPath 獲取當前正在執行的服務器應用程序的根目錄的物理文件系統路徑
            String targetPhysicalFilePath = HttpContext.Current.Request.PhysicalApplicationPath + "ReligionFile/" + directoryName;
            //不存在就創建
            if (!Directory.Exists(targetPhysicalFilePath))
            {
                Directory.CreateDirectory(targetPhysicalFilePath);
            }

            //獲取上傳文件集合
            HttpFileCollection fileCollection = context.Request.Files;
            //HttpPostedFile temp = context.Request.Files["regfile"];//測試
            //String tempe = context.Request.Params["regfile"];
            //HttpPostedFileWrapper fileWrapper = context.Request.Files[0];

            Model.FileInfo tempFileInfo = null;
            if (fileCollection.Count > 0)
            {
                HttpPostedFile item = null;
                for (int i = 0; i < fileCollection.Count; i++)
                {
                    item = fileCollection[i];
                    String suffix = item.FileName.Split('.')[item.FileName.Split('.').Length - 1];//獲取文件的后綴名
                    tempFileInfo = new Model.FileInfo();
                    tempFileInfo = (Model.FileInfo)BeanUtil.PropCopy(fileInfo, tempFileInfo);
                    //tempFileInfo.set_Id(CommonUtil.CreateObjectId());這樣設置Id是無效的
                    tempFileInfo.setName(item.FileName);//存的是以前的文件名, 是否有意義
                    tempFileInfo.setFileCode();
                    tempFileInfo.setType(suffix);
                    tempFileInfo.setCreateTime();
                    suffix = "." + suffix;
                    if (suffix.ToLower().Equals(".txt"))
                    {
                        suffix = ".doc";//這里是否有必要? 這是個問題
                    }
                    String realFileName = Guid.NewGuid().ToString() + suffix;
                    tempFileInfo.setTypeCode(tempFileInfo.getTypeCode() + ":" + "ReligionFile/" + directoryName + "/" + realFileName);
                    tempFileInfo.setPath("ReligionFile/" + directoryName + "/" + realFileName);
                    item.SaveAs(context.Server.MapPath(targetSavePath + directoryName + "/" + realFileName));//文件轉存 必須是文件的根目錄, 而且不能使虛擬目錄
                    fileInfoList.Add(tempFileInfo);
                }
                //foreach (String key in fileCollection) {
                //這里前台只有一個文件選擇框, 那么多文件時keys都是相同的,
                //    HttpPostedFile item = fileCollection[key];
                //    String suffix = item.FileName.Split('.')[item.FileName.Split('.').Length - 1];//獲取文件的后綴名
                //    fileInfo.setName(item.FileName);
                //    fileInfo.setFileCode();
                //    fileInfo.setType(suffix);
                //    fileInfo.setCreateTime();
                //    suffix = "." + suffix;
                //    if (suffix.ToLower().Equals(".txt")) {
                //        suffix = ".doc";//這里是否有必要? 這是個問題
                //    }
                //    String realFileName = Guid.NewGuid().ToString() + suffix;
                //    fileInfo.setTypeCode(fileInfo.getTypeCode() + ":" + "ReligionFile/" + directoryName + realFileName);
                //    item.SaveAs(context.Server.MapPath(targetSavePath + directoryName + "/" + realFileName));//文件轉存 必須是文件的根目錄, 而且不能使虛擬目錄
                //    fileInfoList.Add(fileInfo);
                //}
                int errorCount = fileInfoService.InsertBatchFileInfo(fileInfoList);//文件信息批量入表, 返回失敗個數
                context.Items.Add("FileUploadErrorCount", errorCount);
                
            }

            return fileInfoList;

        }

        /// <summary>
        /// Base64格式的圖片上傳
        /// </summary>
        /// <param name="context"></param>
        public void Insert_Base64_Img(HttpContext context)
        {
            vo.Base64Image base64Image = base.GetInstance<vo.Base64Image>(context, new vo.Base64Image());
            if (base.IsEmpty(base64Image.Base64String))
            {
                NoParams<vo.Base64Image>(context, "上傳參數存在空值");
            }
            else
            {
                List<Model.FileInfo> fileInfoList = util.ImageUtil.Base64ImageInsertBatch(context, util.ArrraysUtil.PurifyArrays<String>(Regex.Split(base64Image.Base64String, "c#", RegexOptions.IgnoreCase)));
                if (fileInfoList.Count > 0)
                {
                    int errorCount = fileInfoService.InsertBatchFileInfo(fileInfoList);
                    int successCount = fileInfoList.Count - errorCount;
                    Success<String>(context, new List<String>() { "一共上傳 " + fileInfoList.Count + "個文件,其中成功 " + successCount + "個,失敗" + errorCount + "" });
                }
                else
                {
                    Error<String>(context, new List<String>() { "上傳失敗: 后台將Base64轉存時失敗" });
                }
            }
        }


        #endregion


        #region 文件刪除

        /// <summary>
        /// 根據ObjectId刪除指定的文件信息
        /// </summary>
        /// <param name="context"></param>
        public void Del_ObjectId(HttpContext context)
        {
            //暫時不做
        }


        /// <summary>
        /// 根據FileCode刪除指定的文件信息
        /// </summary>
        /// <param name="context"></param>
        public void Del_FileCode(HttpContext context)
        {
            Model.FileInfo fileInfo = this.InitFileInfo(context, -1);
            fileInfo = fileInfoService.FindFileInfoByFileCode(fileInfo.getFileCode());
            if (fileInfo != null)
            {
                if (fileInfoService.RemoveFileInfoByFileCode(fileInfo.getFileCode()))
                {
                    RemoveLocalFile(fileInfo);
                    Success<Model.FileInfo>(context, new List<Model.FileInfo>() { fileInfo });
                }
                else
                {
                    Error<Model.FileInfo>(context, new List<Model.FileInfo>() { fileInfo });
                }
            }
            else
            {
                NoParams<Model.FileInfo>(context, "該條記錄不存在,無法刪除");
            }
        }

        /// <summary>
        /// 根據外鍵ForeignKey刪除所關聯的文件信息
        /// </summary>
        /// <param name="context"></param>
        public void Del_ForeignKey(HttpContext context)
        {

        }

        /// <summary>
        /// 根據傳遞進來的FileInfo的path字段刪除服務器上對應的文件
        /// </summary>
        /// <param name="fileInfo"></param>
        private void RemoveLocalFile(Model.FileInfo fileInfo)
        {
            System.Diagnostics.Debug.WriteLine(HttpContext.Current.Request.PhysicalApplicationPath + fileInfo.getPath());
            //FileUtil.RemoveFile(context.Request.PhysicalApplicationPath + fileInfo.getPath());
            FileUtil.RemoveFile(HttpContext.Current.Request.PhysicalApplicationPath + fileInfo.getPath());
        }

        #endregion

        #region 文件修改

        /// <summary>
        /// 根據FileCode修改指定的文件信息
        /// </summary>
        /// <param name="context"></param>
        public void Update_FileCode(HttpContext context)
        {
            Model.FileInfo target = InitFileInfo(context, -1);
            String fileCode = target.getFileCode();
            List<Model.FileInfo> list = null;
            if (CommonUtil.IsEmpty(target.getForeignKey()) || CommonUtil.IsEmpty(target.getFileCode()))
            {
                NoParams<Model.FileInfo>(context, "關聯外鍵ForeignKey或FileCode為空");
            }
            else
            {
                list = FileInsert(context, InitFileInfo(context, 0));
            }
            if (null != list)
            {
                target = list[0];
                target.FileCode = fileCode;
                Model.FileInfo source = fileInfoService.FindFileInfoByFileCode(target.getFileCode());
                if (null != source)
                {
                    target._id = source._id;
                    target.Access = source.Access;
                    target.ForeignKey = source.ForeignKey;
                    if (fileInfoService.UpdateAllByFileCode(target))
                    {
                        RemoveLocalFile(source);//如果上傳成功, 就將原來的文件刪除
                        Success<Model.FileInfo>(context, new List<Model.FileInfo>() { fileInfoService.FindFileInfoByFileCode(target.FileCode) });
                    }
                    else
                    {
                        Error<Model.FileInfo>(context, new List<Model.FileInfo>() { target });
                        RemoveLocalFile(target);//如果更新失敗, 就將上傳的文件刪除
                    }
                }
                else
                {
                    Init<Model.FileInfo>(context, "300", "", new List<Model.FileInfo>() { });
                }
            }
        }

        #endregion


        #region 文件查找

        /// <summary>
        /// 根據FileCode查找指定的文件信息
        /// </summary>
        /// <param name="context"></param>
        public void Query_FileCode(HttpContext context)
        {
            Model.FileInfo fileInfo = fileInfoService.FindFileInfoByFileCode(this.InitFileInfo(context, -1).FileCode);
            if (fileInfo == null)
            {
                NoParams<Model.FileInfo>(context, "該記錄不存在");
            }
            else
            {
                Success<Model.FileInfo>(context, new List<Model.FileInfo>() { fileInfo });
            }
        }

        /// <summary>
        /// 根據ForeignKey查詢所有的文件信息
        /// </summary>
        /// <param name="context"></param>
        public void Query_Foreign(HttpContext context)
        {
            //Model.FileInfo info = this.InitFileInfo(context, -1);
            List<Model.FileInfo> list = fileInfoService.FindFileInfoListByForeignKey(this.InitFileInfo(context, -1).ForeignKey);
            //if (list == null || list.Count == 0) {
            //    NoParams<Model.FileInfo>(context, "沒有匹配的記錄");
            //} else {
            //    Success<Model.FileInfo>(context, list);
            //}
            Success<Model.FileInfo>(context, list);
        }

        #endregion
        //初始化FileInfo
        private Model.FileInfo InitFileInfo(HttpContext context, int access)
        {
            Model.FileInfo fileInfo = ParametersUtil.GetInstanceFormRequest<Model.FileInfo>(context, new Model.FileInfo());//這里主要是獲取ForeignKey

            if (access != -1)
            {
                fileInfo.setAccess(access);//設置文件資源類型  {0表示關聯; 1表示獨立資源,沒有關聯} -1表示不作處理
            }
            return fileInfo;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM