• 下载方法收集


    1.方法一:WebRequest下载,下载路径包含http

     /// <summary>
            /// 网络文件下载
            /// </summary>
            /// <param name="p_strUrl">网络地址</param>
            /// <param name="saveFileName">文件名称</param>
            /// <returns>true-下载成功  false-下载失败</returns>
            /// </remarks>
            public static bool FileDownload(string p_strUrl, string saveFileName)
            {
                try
                {
                    WebRequest webRequest = WebRequest.Create(p_strUrl);
                    //读取文件流
                    Stream stream = webRequest.GetResponse().GetResponseStream();
    
                    byte[] fileByte = new byte[512];
    
                    MemoryStream ms = new MemoryStream();
                    int index = 0;
                    while (true)
                    {
                        index = stream.Read(fileByte, 0, fileByte.Length);
                        if (index == 0)
                        {
                            break;
                        }
                        //写进内存流
                        ms.Write(fileByte, 0, index);
                    }
                    byte[] array = ms.ToArray();
                    saveFileName = string.IsNullOrEmpty(saveFileName) == true ? p_strUrl.Split('/')[p_strUrl.Split('/').Length - 1] : saveFileName;
                     //添加文件头
                    // 判断浏览器类型添加文件头 update by X.Y
                    if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1)
                    {
                        saveFileName = ToHexString(saveFileName);
                    }
                    if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
                    {
                        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="" + saveFileName + """);
                    }
                    else
                    {
                        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + saveFileName);
                    }
                    System.Web.HttpContext.Current.Response.AddHeader("Content-Length", array.Length.ToString());
                    System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
                    System.Web.HttpContext.Current.Response.Charset = "UTF-8";
                    System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    System.Web.HttpContext.Current.Response.BinaryWrite(array);
                    System.Web.HttpContext.Current.Response.Flush();
                    System.Web.HttpContext.Current.Response.Clear();
                }
                catch
                {
                    return false;
                }
    
                return true;
            }
    View Code

    2.方法二:文件流下载方法,下载路径不包含http

    /// <summary>
            /// 功能: 输出文件
            /// </summary>
            /// <param name="fileHttpUrl">文件网络地址</param>
            /// <param name="saveFileName">保存默认文件名</param>
            public void ResponseWriteFile(string fileHttpUrl, string saveFileName)
            {
                try
                {
                    // 创建文件信息实体
                    FileInfo fileInfo = new FileInfo(fileHttpUrl);
                    saveFileName = string.IsNullOrEmpty(saveFileName) == true ? fileHttpUrl.Split('/')[fileHttpUrl.Split('/').Length - 1] : saveFileName;
    
                    if (fileInfo.Exists == true)
                    {
                        //每次只读取100K
                        const long unitSize = 102400;
                        byte[] buffer = new byte[unitSize];
    
                        // 清空Response
                        HttpContext.Current.Response.Clear();
    
                        // 创建文件流
                        FileStream fileStream = File.OpenRead(fileHttpUrl);
                        long fileLength = fileStream.Length;
    
                        HttpContext.Current.Response.ContentType = "application/octet-stream";
    
                        // 判断浏览器类型添加文件头
                        if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1)
                        {
                            saveFileName = ToHexString(saveFileName);
                        }
                        if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
                        {
                            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="" + saveFileName + """);
                        }
                        else
                        {
                            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + saveFileName);
                        }
    
                        // 循环输出文件
                        while (fileLength > 0 && HttpContext.Current.Response.IsClientConnected)
                        {
                            int readLength = fileStream.Read(buffer, 0, Convert.ToInt32(unitSize));
                            HttpContext.Current.Response.OutputStream.Write(buffer, 0, readLength);
                            HttpContext.Current.Response.Flush();
                            fileLength = fileLength - readLength;
                        }
    
                        HttpContext.Current.Response.Close();
                    }
                    else
                    {
                     //("下载失败,文件不存在!");
                    }
                }
                catch(Exception ex)
                {
                   
                  //("下载失败,请联系管理员或重试!");
                }
            }
    View Code


    3.编码

            /// <summary>
            /// Encodes non-US-ASCII characters in a string.
            /// </summary>
            /// <param name="s"></param>
            /// <returns></returns>
            public static string ToHexString(string s)
            {
                char[] chars = s.ToCharArray();
                StringBuilder builder = new StringBuilder();
                for (int index = 0; index < chars.Length; index++)
                {
                    bool needToEncode = NeedToEncode(chars[index]);
                    if (needToEncode)
                    {
                        string encodedString = ToHexString(chars[index]);
                        builder.Append(encodedString);
                    }
                    else
                    {
                        builder.Append(chars[index]);
                    }
                }
    
                return builder.ToString();
            }
    
            /// <summary>
            /// Determines if the character needs to be encoded.
            /// </summary>
            /// <param name="chr"></param>
            /// <returns></returns>
            private static bool NeedToEncode(char chr)
            {
                string reservedChars = "$-_.+!*'(),@=&";
    
                if (chr > 127)
                    return true;
                if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
                    return false;
    
                return true;
            }
    
            /// <summary>
            /// Encodes a non-US-ASCII character.
            /// </summary>
            /// <param name="chr"></param>
            /// <returns></returns>
            private static string ToHexString(char chr)
            {
                UTF8Encoding utf8 = new UTF8Encoding();
                byte[] encodedBytes = utf8.GetBytes(chr.ToString());
                StringBuilder builder = new StringBuilder();
                for (int index = 0; index < encodedBytes.Length; index++)
                {
                    builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
                }
    
                return builder.ToString();
            }
    View Code
  • 相关阅读:
    Hadoop集群搭建记录 | 云计算[CentOS7] | 伪分布式集群 Java环境配置(Oracle JDK)
    [leetcode] 2049 统计最高分的节点数目 | dfs二叉树
    [Linux] 输入命令ls laF后的各字段含义解析
    [leetcode] 432. 全 O(1) 的数据结构 | STL 双向链表&哈希
    Hadoop集群搭建记录 | 云计算[CentOS7] | 伪分布式集群 Hadoop安装配置
    [leetcode] 2024. 考试的最大困扰度 | 双指针
    Hadoop集群搭建记录 | 云计算[CentOS7] | 伪分布式集群[主机名与ip映射+修改配置文件]
    [leetcode] 2039. 网络空闲的时刻 | BFS
    []Linux中rpm命令详解
    Hadoop集群搭建记录 | 云计算[CentOS7] | Eclipse安装并创建第一个项目
  • 原文地址:https://www.cnblogs.com/blog4xy/p/3443478.html
Copyright © 2020-2023  润新知