C# 大文件分段上传,下载

来源:互联网 发布:游戏编程精粹9 pdf 编辑:程序博客网 时间:2024/05/21 09:01

1》客户端 分段上传方法

        public static readonly int G_BLOCK_LEN_PER = 2 * 1024 * 1024;        private void UploadZipMap(string upLoadZipFilePath, string upLoadZipFileName)        {            FileStream fileStream = null;            try            {                using (fileStream = new FileStream(upLoadZipFilePath, FileMode.Open, FileAccess.Read))                {                    long FileLength = fileStream.Length;                    List<long> PkgList = new List<long>();                    long PkgNum = FileLength / Convert.ToInt64(G_BLOCK_LEN_PER);                    for (long iIdx = 0; iIdx < FileLength / Convert.ToInt64(G_BLOCK_LEN_PER); iIdx++)                    {                        PkgList.Add(Convert.ToInt64(G_BLOCK_LEN_PER));                    }                    long s = FileLength % G_BLOCK_LEN_PER;                    if(s != 0)                    {                        PkgList.Add(s);                    }                    for (long iPkgIdx = 0; iPkgIdx < PkgList.Count; iPkgIdx++)                    {                        long bufferSize = PkgList[(int)iPkgIdx];                        byte[] buffer = new byte[bufferSize];                        int bytesRead = fileStream.Read(buffer, 0, (int)bufferSize);                        if (iPkgIdx == 0)                        {                            Webservice_Map_Sync_Mgr.Instance.ws_UPLoadOffLineMap_Sync_Ex(buffer, upLoadZipFileName, true);                        }                        else                        {                            Webservice_Map_Sync_Mgr.Instance.ws_UPLoadOffLineMap_Sync_Ex(buffer, upLoadZipFileName, false);                        }                    }                }            }            catch (Exception ex)            {                LogMgr.Instance.WriteInfo("FileMgr : FileToByte_Ex ->异常: " + ex, true);            }            finally            {                if (fileStream != null)                {                    //关闭资源                      fileStream.Close();                }            }        }

2》WebService 上传方法

        //@ 文件虚拟路线        private string MapPath = @"./MapFiles/";        /// <summary>        ///  上传        /// </summary>        /// <param name="BurferBytes">文件流</param>        /// <param name="FileName">文件名</param>        /// <param name="IfCreate">是否创建?(操作)</param>        /// <returns></returns>        [WebMethod(Description = "UPLoadOffLineMap")]        public string UPLoadOffLineMap(byte[] BurferBytes, string FileName, bool IfCreate)        {            string strJsonContent = string.Empty;            BaseResponse response = new BaseResponse();            try            {                if (BurferBytes.Length == 0) throw new Exception("上传字节数组长度为0");                //@! 存储文件路径                string filePath = Server.MapPath(MapPath);                if (false == Directory.Exists(filePath))                    Directory.CreateDirectory(filePath);                long length = FileWriteOp(BurferBytes, FileName, IfCreate, filePath);                response.STATUS = true;                response.MESSAGE = string.Format("写入文件长度 {0}", length.ToString());            }            catch (Exception ex)            {                response.STATUS = false;                response.MESSAGE = ex.Message;                logger.ErrorException("文件上传-》异常:", ex);            }            finally            {                strJsonContent = response.ToJson();            }            return strJsonContent;        }

3》BaseResponse 类 (服务端跟客户端都已用)

using Newtonsoft.Json;using System;namespace Test.Model{    public class BaseResponse    {        protected bool m_Status = false;        /// <summary>        /// 状态        /// </summary>        public bool STATUS        {            get { return m_Status; }            set { m_Status = value; }        }        protected string m_Message = string.Empty;        public string MESSAGE        {            get { return m_Message; }            set { m_Message = value; }        }        protected ClassInfoObj m_ClassInfo_Obj = null;        public ClassInfoObj CLASSINFO_OBJ        {            get { return m_ClassInfo_Obj; }            set { m_ClassInfo_Obj = value; }        }        public string ToJson()        {            string Json = string.Empty;            try            {                Json = JsonConvert.SerializeObject(this);            }            catch(Exception ex)            {                Json = string.Empty;            }            return Json;        }    }    public class ClassInfoObj    {        protected string m_ClassName = string.Empty;        public string CLASSNAME        {            get { return m_ClassName; }            set { m_ClassName = value; }        }        protected string m_ClassJson = string.Empty;        public string CLASSJSON        {            get { return m_ClassJson; }            set { m_ClassJson = value; }        }    }    public class FileInfoClass    {        public FileInfoClass(string FileName, long FileLength)        {            this.m_FileName = FileName;            this.m_FileLength = FileLength;        }        /// <summary>        /// 文件名        /// </summary>        protected string m_FileName = string.Empty;        public string FileName        {            get { return m_FileName; }            set { m_FileName = value; }        }        /// <summary>        ///  文件长度        /// </summary>        protected long m_FileLength = 0;        public long FileLength        {            get { return m_FileLength; }            set { m_FileLength = value; }        }        public string ToJson()        {            string Json = string.Empty;            try            {                Json = JsonConvert.SerializeObject(this);            }            catch (Exception ex)            {                Json = string.Empty;            }            return Json;        }    }}

4》WebService 下载方法

        /// <summary>        /// 文件下载        /// </summary>        /// <param name="pFilePath">文件路径</param>        /// <param name="pFileName">文件名称</param>        /// <param name="PosOffset">文件偏移位置</param>        /// <param name="BlockLength">下载长度</param>        /// <returns></returns>        [WebMethod(Description = "下载文件字节(DNLoadOffLineMap)")]        public string DNLoadOffLineMap(string FileName,long PosOffset,int BlockLength)        {            GisBaseResponse Response = new GisBaseResponse();            string strJsonContent = string.Empty;            FileStream FileStream = null;            try            {                string pFilePaths = Server.MapPath(MapPath);                if (BlockLength > 16 * 1024) throw new Exception("下载文件分块大小大于16KB");                string strFilePath = Path.Combine(pFilePaths, FileName);                if (false == File.Exists(strFilePath)) throw new Exception(string.Format("失败 :未能找到 {0} 文件!",strFilePath));                string strBase64 = string.Empty;                using (FileStream = File.Open(strFilePath, FileMode.Open, FileAccess.Read))                {                    FileStream.Seek(PosOffset, SeekOrigin.Begin);                    byte[] bufferBytes = new byte[BlockLength];                    int readLength = FileStream.Read(bufferBytes, 0, bufferBytes.Length);                    strBase64 = Convert.ToBase64String(bufferBytes);                }                Response.STATUS = true;                Response.MESSAGE = strBase64;            }            catch(Exception ex)            {                string strErrMsg = ex.Message;                Response.STATUS = false;                Response.MESSAGE = strErrMsg;            }            finally            {                strJsonContent = JsonConvert.SerializeObject(Response);                if(null != FileStream)                {                    FileStream.Close();                    FileStream = null;                }            }            return strJsonContent;        }---------------------------------------------------------------------------------------        /// <summary>        /// 先获取文件信息再进行下载        /// </summary>        /// <param name="pFilePath">文件路径</param>        /// <param name="FileName">文件名称</param>        /// <returns></returns>        [WebMethod(Description = "获取文件信息")]        public string GetFileInfo(string FileName)        {            string strJsonContent = string.Empty;            GisBaseResponse oResponse = new GisBaseResponse();            try            {                string pFilePaths = Server.MapPath(MapPath);                //@! 保存文件                string strFileName = Path.Combine(pFilePaths, FileName);                if (false == File.Exists(strFileName))                {                    oResponse.STATUS = false;                    oResponse.MESSAGE = "失败 :未能找到文件!";                }                FileInfo oFileInfo = new FileInfo(strFileName);                FileInfoClass oFileInfoClass = new FileInfoClass(oFileInfo.Name, oFileInfo.Length);                oResponse.STATUS = true;                oResponse.MESSAGE = string.Empty;                ClassInfoObj oContent = new ClassInfoObj();                oContent.CLASSNAME = oFileInfoClass.GetType().Name;                oContent.CLASSJSON = oFileInfoClass.ToJson();                oResponse.CLASSINFO_OBJ = oContent;            }            catch (Exception ex)            {                while (ex.InnerException != null)                    ex = ex.InnerException;                logger.ErrorException("获取文件信息出现错误.", ex);                oResponse.STATUS = false;                oResponse.MESSAGE = "异常:" + ex.Message;            }            finally            {                strJsonContent = oResponse.ToJson();            }            return strJsonContent;        }

5》客户端 分段下载 方法

  private void Download(string fileName , string outFolder)        { //string fileName = "test.zip"; //string outFolder= @"C:\";                    //@!获取Webservice文件信息                    string strJson = Webservice_Map_Sync_Mgr.Instance.ws_DownloadOffLineMapFileName_Sync(fileName);                    GisBaseResponse oGisBaseResponse = GetJson.ToGisBaseResponse(strJson);                    FileInfoClass oFileInfoClass = GetJson.ToFileInfoClass(oGisBaseResponse);                    const int G_BLOCK_LEN_PER = 16 * 1024; //下载16KB                    if (true == oGisBaseResponse.STATUS)                    {                        long FileLength = oFileInfoClass.FileLength;                        List<long> PkgList = new List<long>();                        long PkgNum = FileLength / Convert.ToInt64(G_BLOCK_LEN_PER);                        for (long iIdx = 0; iIdx < FileLength / Convert.ToInt64(G_BLOCK_LEN_PER); iIdx++)                        {                            PkgList.Add(Convert.ToInt64(G_BLOCK_LEN_PER));                        }                        long s = FileLength % G_BLOCK_LEN_PER;                        if (s != 0)                        {                            PkgList.Add(s);                        }                        for (long iPkgIdx = 0; iPkgIdx < PkgList.Count; iPkgIdx++)                        {                            long bufferSize = PkgList[(int)iPkgIdx];                            if (iPkgIdx == 0)                            {                                FileOperation_Ex(iPkgIdx * G_BLOCK_LEN_PER, fileName, G_BLOCK_LEN_PER, true, outFolder);                            }                            else                            {                                FileOperation_Ex(iPkgIdx * G_BLOCK_LEN_PER, fileName, G_BLOCK_LEN_PER, false, outFolder);                            }                        }                    }

6》FileOperation_Ex 方法

        /// <summary>        /// 文件操作        /// </summary>        /// <param name="fileBt">文件流</param>        /// <param name="fileName">文件名</param>        /// <param name="ifCreate">是否创建?(操作)</param>        /// <param name="FilePath">文件路径</param>        /// <returns>返回文件长度</returns>        private long FileOperation_Ex(long FileOffset, string FileName, int DownLength, bool ifCreate, string FilePath)        {            string JsonRet =Webservice_Map_Sync_Mgr.Instance.ws_DownloadOffLineMap_Snc(FileName, FileOffset, DownLength);            GisBaseResponse oGisBaseResponse = GetJson.ToGisBaseResponse(JsonRet);            byte[] myByteFile = Convert.FromBase64String(oGisBaseResponse.MESSAGE);            long lWriteLength = -1;            FileStream fstream = null;            try            {                FileMode fileMode = (ifCreate) ? FileMode.Create : FileMode.Append;                //@! 是否创建新文件                fstream = new FileStream(FilePath + FileName, fileMode);                //@! 二进制转换成文件                fstream.Write(myByteFile, 0, myByteFile.Length);                lWriteLength = fstream.Length;            }            catch (Exception ex)            {                lWriteLength = -1;            }            finally            {                fstream.Close();            }            return lWriteLength;        }

7》Webservice 同步异步_学习

[学习1]
(http://blog.csdn.net/wayne20018891/article/details/7587347)

[学习2]
(http://www.cnblogs.com/menglin2010/archive/2012/03/30/2423679.html)

0 0