公共上传文件类

今天心里挺烦的,正好抽这间把把自己写的上传文件的公用类贡献出来,让大家做个参考。也给希望高手能提出好的建议。

using System;
using System.Collections.Generic;
using System.IO;
using System.Web;

namespace Common.FilesManagement
{
    public class UploadFiles
    {
        #region field
        private int _allowFileSize = 1024 * 1024 * 100;                         //默认文件容量大小
        private List<string> _prohibitFileType=new List<string>();              //禁止的文件类型,扩展名
        private List<string> _allowFileType = new List<string>();               //允许的文件类型,扩展名
        private bool _allowCreateFolder = true;                                 //是否允许创建子文件夹
        private bool _allowReName = true;                                       //是否允许生成新的文件名
        private HttpPostedFile _httpPostedFile;
        #endregion
        public UploadFiles(HttpPostedFile httppostedfile) 
        {
            _httpPostedFile = httppostedfile;
        }
        #region porperty
        public int AllowFileSize { get { return _allowFileSize; } set { _allowFileSize = value; } }//允许上传文件的大小
        public int FileSize { get; private set; }       //上传文件的实际容量
        public string FilePrefix { get; set; }          // 自定规则 文件名前缀
        public bool AllowCreateFolder { get { return _allowCreateFolder; } set { _allowCreateFolder = value; } }
        public bool AllowReName { get { return _allowReName; } set { _allowReName = value; } }

        
        #endregion
        #region method
        /// <summary>
        /// 禁止文件类型
        /// </summary>
        /// <param name="fileType"></param>
        public void AddProhibitFileType(string fileType) 
        {
            _prohibitFileType.Add(fileType.ToLower());
        }
        /// <summary>
        /// 允许的文件类型
        /// </summary>
        /// <param name="filetype"></param>
        public void AddAllowFileType(string filetype)
        {
            _allowFileType.Add(filetype.ToLower());
        } 
        /// <summary>
        /// 获得新的文件名
        /// </summary>
        /// <returns>返回新的文件名</returns>
        protected string NewFileName(string OldFileName)
        {
            string year = System.DateTime.Now.Year.ToString();
            string month = System.DateTime.Now.Month.ToString();
            string day = System.DateTime.Now.Day.ToString();
            string hour = System.DateTime.Now.Hour.ToString();
            string minute = System.DateTime.Now.Minute.ToString();
            string second = System.DateTime.Now.Second.ToString();
            string minsecond = System.DateTime.Now.Millisecond.ToString();
            System.Random rand = new System.Random();
            string random = rand.Next(1000).ToString();
            string Extension = FileExtension(OldFileName);
            string newfile = FilePrefix + "_" + year + month + day + hour + minute + second + minsecond + random + Extension;
            return newfile;
        }
        //扩展名
        private string FileExtension(string OldFileName)
        {
            string Extension = OldFileName.Substring(OldFileName.LastIndexOf("."), OldFileName.Length - OldFileName.LastIndexOf("."));
            return Extension.ToLower();
        }
        protected string GetFileName() 
        {
            if (!_allowReName)
                return _httpPostedFile.FileName;
            else
                return NewFileName(_httpPostedFile.FileName);
        }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="folderPath">要创建文件夹的物理路径</param>
        /// <returns>返回创建后的路径</returns>
        private string CreateFolder(string folderPath)
        {
            string strFolderName = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString();
            folderPath = folderPath + "/" + strFolderName;
            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);
            return strFolderName;
        }
        /// <summary>
        /// 判断文件是否是允许的类型
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        private bool IsFileType(string filename) 
        {
            string fileExtension = FileExtension(filename);
            if (_prohibitFileType != null&&_prohibitFileType.Count>0)
            {
                if (_prohibitFileType.Contains(fileExtension))
                {
                    return false;
                }
            }
            if (_allowFileType != null&&_allowFileType.Count>0)
            {
                if (!_allowFileType.Contains(fileExtension))
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 验证,并上传文件
        /// </summary>
        /// <param name="storagePath">文件存储路径</param>
        /// <param name="IsSuccess">上传状态</param>
        /// <returns>返回,上传文件后的文件名</returns>
        public string Upload(string storagePath,ref bool IsSuccess)
        {
            IsSuccess = false;
            HttpPostedFile httpPostedFile = _httpPostedFile;
            if (httpPostedFile != null)
            {
                string strFileName=VerifyFile(ref IsSuccess, httpPostedFile);
                if (IsSuccess)
                {
                    try
                    {
                        return CreateFile(storagePath, ref IsSuccess, httpPostedFile, strFileName);
                    }
                    catch (Exception) { IsSuccess = false; return "上传错误"; throw; }
                }
                else 
                {
                    IsSuccess = false; return "上传错误";
                }
            }
            else 
            {
                IsSuccess = false;
                return "上传错误 HttpPostedFile对像为空";
            }
        }
        /// <summary>
        /// 确认文件是否可以上传
        /// </summary>
        /// <param name="IsSuccess">状态</param>
        /// <param name="httpPostedFile">System.Web.HttpPostedFile</param>
        /// <returns>返回验证后信息。如果验证通过,返回文件名</returns>
        private string VerifyFile(ref bool IsSuccess, HttpPostedFile httpPostedFile)
        {
            string strFileName = GetFileName();
            if (!IsFileType(strFileName))
            {
                IsSuccess = false; return "不支持此文件类型";
            }
            FileSize = httpPostedFile.ContentLength;
            if (FileSize < 1 || FileSize >= _allowFileSize)
            {
                IsSuccess = false; return "文件大小已超过允许的范围";
            }
            else
            {
                IsSuccess = true; return strFileName;
            }
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="storagePath">存储路径</param>
        /// <param name="IsSuccess">是否成功状态</param>
        /// <param name="httpPostedFile">System.Web.HttpPostedFile</param>
        /// <param name="strFileName">文件名</param>
        /// <returns>返回创建后的文件名</returns>
        private string CreateFile(string storagePath, ref bool IsSuccess, HttpPostedFile httpPostedFile, string strFileName)
        {
            string strNewStoragePath = storagePath;
            string strFolder = "";
            if (_allowCreateFolder)
                strFolder = "/" + CreateFolder(storagePath);
            string strFilePath = strNewStoragePath + strFolder + "/" + strFileName;
            Stream stream = httpPostedFile.InputStream;
            SaveFile(stream, strFilePath);
            IsSuccess = true;
            return strFolder + "/" + strFileName;
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="streamPara">文件流</param>
        /// <param name="strFilePath">文件路径与文件名</param>
        private static void SaveFile(Stream streamPara, string strFilePath)
        {
            Stream stream = streamPara;
            byte[] by = new byte[1024];//分块读取
            FileStream fileStream = new FileStream(strFilePath, FileMode.Create);
            int isize = stream.Read(by, 0, by.Length);
            while (isize > 0)
            {
                if (isize > 0)
                {
                    fileStream.Write(by, 0, isize);
                }
                isize = stream.Read(by, 0, by.Length);
            }
            fileStream.Close();
            fileStream.Dispose();
        }
        #endregion

        
    }
}

逻辑代码如下

public string UploadFile(System.Web.HttpPostedFile httpPostedFile,string path,ref bool IsSuccess)
        {
            Common.FilesManagement.UploadFiles uploadfile = new Common.FilesManagement.UploadFiles(httpPostedFile);
            uploadfile.FilePrefix = "CM";
            uploadfile.AllowReName = false;
            uploadfile.AllowCreateFolder = false;
            uploadfile.AddProhibitFileType(".exe");
            uploadfile.AddAllowFileType(".jpg");
            return uploadfile.Upload(path,ref IsSuccess);
        }

调用方式如下

public JsonResult UploadFile() 
         {
             bool bresult = false;
             string strMsg = "上传失败";
             string strFileName = "";
             HttpPostedFile file = System.Web.HttpContext.Current.Request.Files["Filedata"];
             string uploadPath = System.Web.HttpContext.Current.Server.MapPath(@Request["folder"]) + "\";
             BLL.Position.CandidatesBll candBll = new BLL.Position.CandidatesBll();

             strFileName = candBll.UploadFile(file, uploadPath, ref bresult);
             if (bresult)
                 strMsg = "上传成功";
             return Json(new { IsSuccess = bresult,fileName=strFileName, Message = strMsg });
         }
View Code

前台代码

<script src="/uploadify/jquery.uploadify.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="/uploadify/uploadify.css">

<div style=" 440px; height: 33px; float: left;">
                        <div style="float: left;">
                            <input id="hidResume" name="hidResume" type="hidden" />
                            <div id="uploadResult" style="float: left; padding: 5px; height: 20px; line-height: 20px;
                                display: block; color: Red;">
                            </div>
                        </div>
                        <div style="float: left;">
                            <div id="queue" style="float: left;">
                            </div>
                            <input id="file_upload" name="file_upload" type="file" multiple="false" style="float: left;
                                 150px;">
                        </div>
                    </div>
<script type="text/javascript">
    var auth = "@(Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)";
    var ASPSESSID = "@Session.SessionID";
        $(function() {
            $('#file_upload').uploadify({
                // 'formData': { 'someKey': 'someValue', 'someOtherKey': 1 },
                'formData': { 'folder': '/uploads', 'ASPSESSID': ASPSESSID, 'AUTHID': auth },
                'swf': '/uploadify/uploadify.swf',
                'uploader': '/Position/UploadFile',
                'uploadLimit': 1,
                'multi': false,
                'buttonText': '浏  览',
                'fileSizeLimit': '5MB',
                'fileTypeExts': '*.doc;*.docx;*.xlsx;*.jpg',
                'fileTypeDesc': '请选择doc docx文件',
                'width': '110',
                'height': '28',
                'onUploadSuccess': function (file, data, response) {
                    //alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
                    var objResult = eval("(" + data + ")");
                    $("#hidResume").val(objResult.fileName);
                    $("#uploadResult").html(objResult.fileName + objResult.Message);
                } 
            });
        });
</script>
View Code
原文地址:https://www.cnblogs.com/cicada/p/3183426.html