05
2015
07

【C#、Asp.Net-工具类大全】文件上传操作工具类

前端页面代码:

<input id="fileUpload" type="file" runat="server" visible="false" />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="sBtn" runat="server" OnClick="sBtn_Click" Text="上传" Visible="false" />

使用C#实例:

/// <summary>
/// 文件上传:对应FileUpload、input两种
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void sBtn_Click(object sender, EventArgs e)
{
    #region 上传文件
    urlPath = Server.MapPath("~/file/");
    FileUpHelper.FileSc(FileUpload1, DateTime.Now.ToString("yyyyMMddHHmmss") + FileDownHelper.FileNameExtension(FileUpload1.FileName), urlPath);
    FileUpHelper.FileUpload(urlPath, DateTime.Now.ToString("yyyyMMddHHmmss") + FileDownHelper.FileNameExtension(FileUpload1.FileName), FileUpload1);
    byte[] by = FileUpload1.FileBytes;
    FileUpHelper.SaveFile(by, DateTime.Now.ToString("yyyyMMddHHmmss"), FileDownHelper.FileNameExtension(FileUpload1.FileName), urlPath);
    FileUpHelper.UploadFile(urlPath, 100 * 1024 * 1024, new string[4] { ".txt", ".rar", ".png", ".jpg" }, fileUpload); //100M内
    string saveFileName = "";
    int fileSize = 0;
    FileUpHelper.UploadFile(urlPath, 100 * 1024 * 1024, new string[4] { ".txt", ".rar", ".png", ".jpg" }, fileUpload, out saveFileName, out fileSize);
    FileUpHelper.UploadFile(urlPath, 100 * 1024 * 1024, new string[4] { ".txt", ".rar", ".png", ".jpg" }, DateTime.Now.ToString("yyyyMMddHHmmss"), fileUpload);
    #endregion
}

类库信息:

/// <summary>
/// 文件上传类(文件另存为)
/// </summary>
public class FileUpHelper
{
    #region 文件流的形式进行上传操作
    #region 基础信息
    /// <summary>
    /// 转换为字节数组
    /// </summary>
    /// <param name="filename">文件名</param>
    /// <returns>字节数组</returns>
    public static byte[] GetBinaryFile(string filename)
    {
        if (File.Exists(filename))
        {
            FileStream Fsm = null;
            try
            {
                Fsm = File.OpenRead(filename);
                return ConvertStreamToByteBuffer(Fsm);
            }
            catch
            {
                return new byte[0];
            }
            finally
            {
                Fsm.Close();
            }
        }
        else
        {
            return new byte[0];
        }
    }
    /// <summary>
    /// 流转化为字节数组
    /// </summary>
    /// <param name="theStream">流</param>
    /// <returns>字节数组</returns>
    public static byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
    {
        int bi;
        MemoryStream tempStream = new System.IO.MemoryStream();
        try
        {
            while ((bi = theStream.ReadByte()) != -1)
            {
                tempStream.WriteByte(((byte)bi));
            }
            return tempStream.ToArray();
        }
        catch
        {
            return new byte[0];
        }
        finally
        {
            tempStream.Close();
        }
    }
    #endregion
    #region 上传文件
    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="PosPhotoUpload">控件</param>
    /// <param name="saveFileName">保存的文件名</param>
    /// <param name="imagePath">保存的文件路径</param>
    public static string FileSc(FileUpload PosPhotoUpload, string saveFileName, string imagePath)
    {
        string state = "";
        if (PosPhotoUpload.HasFile)
        {
            if (PosPhotoUpload.PostedFile.ContentLength / 1024 < 10240)
            {
                string MimeType = PosPhotoUpload.PostedFile.ContentType;
                if (String.Equals(MimeType, "image/gif") || String.Equals(MimeType, "image/pjpeg") || String.Equals(MimeType, "image/png") || String.Equals(MimeType, "image/jpeg"))
                {
                    string extFileString = System.IO.Path.GetExtension(PosPhotoUpload.PostedFile.FileName);
                    PosPhotoUpload.PostedFile.SaveAs(imagePath + saveFileName);
                }
                else
                {
                    state = "上传文件类型不正确";
                }
            }
            else
            {
                state = "上传文件不能大于10M";
            }
        }
        else
        {
            state = "没有上传文件";
        }
        return state;
    }
    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="path">保存路径</param>
    /// <param name="fileName">上传后文件名</param>
    /// <param name="filleupload">上传文件控件</param>
    /// <returns></returns>
    public static string FileUpload(string path, string fileName, FileUpload filleupload)
    {
        try
        {
            bool fileOk = false;
            //取得文件的扩展名,并转换成小写
            string fileExtension = System.IO.Path.GetExtension(filleupload.FileName).ToLower();
            //文件格式
            string[] allowExtension = { ".rar", ".zip", ".rar", ".ios", ".jpg", ".png", "bmp", ".gif", ".txt" };
            if (filleupload.HasFile)
            {
                //对上传的文件的类型进行一个个匹对
                for (int i = 0; i < allowExtension.Length; i++)
                {
                    if (fileExtension == allowExtension[i])
                    {
                        fileOk = true;
                        break;
                    }
                }
            }
            //如果符合条件,则上传
            if (fileOk)
            {
                if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(path);
                }
                if (!FileHelper.IsExistFile(path + fileName))
                {
                    int Size = filleupload.PostedFile.ContentLength / 1024 / 1024;
                    if (Size > 10)
                    {
                        return "上传失败,文件过大";
                    }
                    else
                    {
                        filleupload.PostedFile.SaveAs(path + fileName);
                        return "上传成功";
                    }
                }
                else
                {
                    return "上传失败,文件已存在";
                }
            }
            else
            {
                return "不支持【" + fileExtension + "】文件格式";
            }
        }
        catch (Exception)
        {
            return "上传失败";
        }
    }
    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="binData">字节数组</param>
    /// <param name="fileName">文件名</param>
    /// <param name="fileType">文件类型</param>
    /// <param name="savePath">保存路径</param>
    //-------------------调用----------------------
    //byte[] by = GetBinaryFile("E:\\Hello.txt");
    //this.SaveFile(by,"Hello",".txt");
    //---------------------------------------------
    public static void SaveFile(byte[] binData, string fileName, string fileType, string savePath)
    {
        FileStream fileStream = null;
        MemoryStream m = new MemoryStream(binData);
        try
        {
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            string File = savePath + fileName + fileType;
            fileStream = new FileStream(File, FileMode.Create);
            m.WriteTo(fileStream);
        }
        finally
        {
            m.Close();
            fileStream.Close();
        }
    }
    #endregion
    #endregion
    #region 文件通过HtmlInputFile控件上传操作
    /// <summary>
    /// 文件进行上传
    /// </summary>
    /// <param name="filePath">保存文件地址</param>
    /// <param name="maxSize">文件最大大小</param>
    /// <param name="fileType">文件后缀类型</param>
    /// <param name="TargetFile">控件名</param>
    /// <returns></returns>
    public static string UploadFile(string filePath, int maxSize, string[] fileType, System.Web.UI.HtmlControls.HtmlInputFile TargetFile)
    {
        string Result = "UnDefine";
        bool typeFlag = false;
        string FilePath = filePath;
        int MaxSize = maxSize;
        string strFileName, strNewName, strFilePath;
        if (TargetFile.PostedFile.FileName == "")
        {
            return "FILE_ERR";
        }
        strFileName = TargetFile.PostedFile.FileName;
        TargetFile.Accept = "*/*";
        strFilePath = FilePath;
        if (Directory.Exists(strFilePath) == false)
        {
            Directory.CreateDirectory(strFilePath);
        }
        FileInfo myInfo = new FileInfo(strFileName);
        string strOldName = myInfo.Name;
        strNewName = strOldName.Substring(strOldName.LastIndexOf("."));
        strNewName = strNewName.ToLower();
        if (TargetFile.PostedFile.ContentLength <= MaxSize)
        {
            for (int i = 0; i <= fileType.GetUpperBound(0); i++)
            {
                if (strNewName.ToLower() == fileType[i].ToString()) { typeFlag = true; break; }
            }
            if (typeFlag)
            {
                string strFileNameTemp = GetUploadFileName();
                string strFilePathTemp = strFilePath;
                float strFileSize = TargetFile.PostedFile.ContentLength;
                strOldName = strFileNameTemp + strNewName;
                strFilePath = strFilePath + "\\" + strOldName;
                TargetFile.PostedFile.SaveAs(strFilePath);
                Result = strOldName + "|" + strFileSize;
                TargetFile.Dispose();
            }
            else
            {
                return "TYPE_ERR";
            }
        }
        else
        {
            return "SIZE_ERR";
        }
        return (Result);
    }
    /// <summary>
    /// 文件进行上传
    /// </summary>
    /// <param name="filePath">保存文件地址</param>
    /// <param name="maxSize">文件最大大小</param>
    /// <param name="fileType">文件后缀类型</param>
    /// <param name="TargetFile">控件名</param>
    /// <param name="saveFileName">保存后的文件名和地址</param>
    /// <param name="fileSize">文件大小</param>
    /// <returns></returns>
    public static string UploadFile(string filePath, int maxSize, string[] fileType, System.Web.UI.HtmlControls.HtmlInputFile TargetFile, out string saveFileName, out int fileSize)
    {
        saveFileName = "";
        fileSize = 0;
        string Result = "";
        bool typeFlag = false;
        string FilePath = filePath;
        int MaxSize = maxSize;
        string strFileName, strNewName, strFilePath;
        if (TargetFile.PostedFile.FileName == "")
        {
            return "请选择上传的文件";
        }
        strFileName = TargetFile.PostedFile.FileName;
        TargetFile.Accept = "*/*";
        strFilePath = FilePath;
        if (Directory.Exists(strFilePath) == false)
        {
            Directory.CreateDirectory(strFilePath);
        }
        FileInfo myInfo = new FileInfo(strFileName);
        string strOldName = myInfo.Name;
        strNewName = strOldName.Substring(strOldName.LastIndexOf("."));
        strNewName = strNewName.ToLower();
        if (TargetFile.PostedFile.ContentLength <= MaxSize)
        {
            string strFileNameTemp = GetUploadFileName();
            string strFilePathTemp = strFilePath;
            strOldName = strFileNameTemp + strNewName;
            strFilePath = strFilePath + strOldName;
            fileSize = TargetFile.PostedFile.ContentLength / 1024;
            saveFileName = FileHelper.GetFileName(strFilePath);
            TargetFile.PostedFile.SaveAs(strFilePath);
            TargetFile.Dispose();
        }
        else
        {
            return "上传文件超出指定的大小";
        }
        return (Result);
    }
    /// <summary>
    /// 文件进行上传
    /// </summary>
    /// <param name="filePath">保存文件地址</param>
    /// <param name="maxSize">文件最大大小</param>
    /// <param name="fileType">文件后缀类型</param>
    /// <param name="filename">要保存为文件名</param>
    /// <param name="TargetFile">控件名</param>
    /// <returns></returns>
    public static string UploadFile(string filePath, int maxSize, string[] fileType, string filename, System.Web.UI.HtmlControls.HtmlInputFile TargetFile)
    {
        string Result = "UnDefine";
        bool typeFlag = false;
        string FilePath = filePath;
        int MaxSize = maxSize;
        string strFileName, strNewName, strFilePath;
        if (TargetFile.PostedFile.FileName == "")
        {
            return "FILE_ERR";
        }
        strFileName = TargetFile.PostedFile.FileName;
        TargetFile.Accept = "*/*";
        strFilePath = FilePath;
        if (Directory.Exists(strFilePath) == false)
        {
            Directory.CreateDirectory(strFilePath);
        }
        FileInfo myInfo = new FileInfo(strFileName);
        string strOldName = myInfo.Name;
        strNewName = strOldName.Substring(strOldName.LastIndexOf("."));
        strNewName = strNewName.ToLower();
        if (TargetFile.PostedFile.ContentLength <= MaxSize)
        {
            for (int i = 0; i <= fileType.GetUpperBound(0); i++)
            {
                if (strNewName.ToLower() == fileType[i].ToString()) { typeFlag = true; break; }
            }
            if (typeFlag)
            {
                string strFileNameTemp = filename;
                string strFilePathTemp = strFilePath;
                strOldName = strFileNameTemp + "." + strNewName;
                strFilePath = strFilePath + strOldName;
                TargetFile.PostedFile.SaveAs(strFilePath);
                Result = strOldName;
                TargetFile.Dispose();
            }
            else
            {
                return "TYPE_ERR";
            }
        }
        else
        {
            return "SIZE_ERR";
        }
        return (Result);
    }
    /// <summary>
    /// 取文件名
    /// </summary>
    /// <returns></returns>
    public static string GetUploadFileName()
    {
        string Result = "";
        DateTime time = DateTime.Now;
        Result += time.Year.ToString() + FormatNum(time.Month.ToString(), 2) + FormatNum(time.Day.ToString(), 2) + FormatNum(time.Hour.ToString(), 2) + FormatNum(time.Minute.ToString(), 2) + FormatNum(time.Second.ToString(), 2) + FormatNum(time.Millisecond.ToString(), 3);
        return (Result);
    }
    /// <summary>
    /// 格式化字符串
    /// </summary>
    /// <param name="Num">需格式的数字</param>
    /// <param name="Bit">0个数</param>
    /// <returns></returns>
    public static string FormatNum(string Num, int Bit)
    {
        int L;
        L = Num.Length;
        for (int i = L; i < Bit; i++)
        {
            Num = "0" + Num;
        }
        return (Num);
    }
    #endregion
}
/// <summary>
/// 文件下载类
/// </summary>
public class FileDownHelper
{
    #region 基础方法
    /// <summary>
    /// 读取虚拟目录文件的文件后缀
    /// </summary>
    /// <param name="fileName">文件虚拟路径</param>
    /// <returns></returns>
    public static string FileNameExtension(string fileName)
    {
        return Path.GetExtension(MapPathFile(fileName));
    }
    /// <summary>
    /// 获取虚拟目录的物理地址
    /// </summary>
    /// <param name="fileName">文件虚拟路径</param>
    /// <returns></returns>
    public static string MapPathFile(string fileName)
    {
        return HttpContext.Current.Server.MapPath(fileName);
    }
    #endregion

    #region 下载文件操作
    /// <summary>
    /// 普通下载
    /// </summary>
    /// <param name="fileName">文件虚拟路径</param>
    public static void DownLoadold(string fileName)
    {
        string destFileName = MapPathFile(fileName);
        if (File.Exists(destFileName))
        {
            FileInfo fi = new FileInfo(destFileName);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Buffer = false;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(destFileName), System.Text.Encoding.UTF8));
            HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.WriteFile(destFileName);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
    }

    /// <summary>
    /// 分块下载
    /// </summary>
    /// <param name="fileName">文件虚拟路径</param>
    public static void DownLoad(string fileName)
    {
        string filePath = MapPathFile(fileName);
        long chunkSize = 204800;             //指定块大小 
        byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区 
        long dataToRead = 0;                 //已读的字节数   
        FileStream stream = null;
        try
        {
            //打开文件   
            stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            dataToRead = stream.Length;

            //添加Http头   
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
            HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());

            while (dataToRead > 0)
            {
                if (HttpContext.Current.Response.IsClientConnected)
                {
                    int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
                    HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.Clear();
                    dataToRead -= length;
                }
                else
                {
                    dataToRead = -1; //防止client失去连接 
                }
            }
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write("Error:" + ex.Message);
        }
        finally
        {
            if (stream != null) stream.Close();
            HttpContext.Current.Response.Close();
        }
    }

    /// <summary>
    ///  输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
    /// </summary>
    /// <param name="request">Page.Request对象</param>
    /// <param name="response">Page.Response对象</param>
    /// <param name="fileName">下载文件名</param>
    /// <param name="filePath">带文件名下载路径</param>
    /// <param name="speed">每秒允许下载的字节数</param>
    /// <returns>返回是否成功</returns>
    //---------------------------------------------------------------------
    //调用:
    // string FullPath=Server.MapPath("count.txt");
    // ResponseFile(this.Request,this.Response,"count.txt",FullPath,100);
    //---------------------------------------------------------------------
    public static bool ResponseFile(HttpRequest request, HttpResponse response, string fileName, string filePath, long speed)
    {
        try
        {
            FileStream myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                response.AddHeader("Accept-Ranges", "bytes");
                response.Buffer = false;

                long fileLength = myFile.Length;
                long startBytes = 0;
                int pack = 10240;  //10K bytes
                int sleep = (int)Math.Floor((double)(1000 * pack / speed)) + 1;

                if (request.Headers["Range"] != null)
                {
                    response.StatusCode = 206;
                    string[] range = request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }

                response.AddHeader("Connection", "Keep-Alive");
                response.ContentType = "application/octet-stream";
                response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (response.IsClientConnected)
                    {
                        response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }
    #endregion
}

显示效果:

不同的文件上传操但大体都差不多。

以上类库内容来源互联网,站长稍作整理


« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。