悉野小楼

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

Asp.net下载文件

网站上的文件是临时文件, 浏览器下载完成, 网站需要将其删除.

下面的写法, 文件读写后没关闭, 经常删除失败.

复制代码
/// <summary>
        /// 下载服务器文件,参数一物理文件路径(含文件名称及后缀),参数二文件名称
        /// </summary>
        /// <param name="PhysicalPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool DownLoad(string PhysicalPath, string fileName)
        {
            bool _bool = false;
            string[] arrSplit = PhysicalPath.Split('.');

            string fileType = arrSplit[arrSplit.Length - 1];//获得下载文件的类型
            try
            {
                if ("xls".Equals(fileType))
                {
                    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                }
                //else if("xml".Equals(fileType))
                //{
                //    HttpContext.Current.Response.ContentType = "application/octet-stream";
                //}
                else
                {
                    HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
                }

                HttpContext.Current.Response.Charset = GlobalVar.ADMIN_CHARSET_ENCODING;
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Utils.UrlEncode(fileName));//设置文件名称 
                HttpContext.Current.Response.TransmitFile(PhysicalPath);
                _bool = true;
            }
            catch
            {

                _bool = false;
            }
            finally
            {
                //发送到客户端的文件流,如果点击取消,此临时文件会一直打开着,无法快速删除,影响不大,之后再行解决
                //  HttpContext.Current.Response.Clear();
                //  HttpContext.Current.Response.Close();
            }

            return _bool;
        }
复制代码


下面是正确写法, 解决用户点击取消, 临时文件还打开着的问题(down临时文件夹可不要)

复制代码
/// <summary>
        /// 下载服务器文件,参数一物理文件路径(含文件名称及后缀),参数二文件名称
        /// </summary>
        /// <param name="PhysicalPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static void DownLoad(string PhysicalPath, string NewFileName)
        {
            //清空下down目录下大于1小时的文件
            string[] files = Directory.GetFiles(Utils.GetMapPath("down"));
            foreach (string str in files)
            {
                FileInfo fileInfo = new FileInfo(str);
                if (Math.Abs((fileInfo.CreationTime - DateTime.Now).TotalHours) > 1)
                {
                    try
                    {
                        File.Delete(str);
                    }
                    catch
                    {
                        Func.SaveLog(3, "删除" + str + "文件失败");
                    }
                }
            }

            //将要下载的文件复制到down临时文件夹
            string strDownFileName = Path.Combine(Utils.GetMapPath("down"), new Random().Next(int.MaxValue).ToString());
            File.Copy(PhysicalPath, strDownFileName, true);

            System.IO.Stream iStream = null;

            // Buffer to read 10K bytes in chunk:
            byte[] buffer = new Byte[10000];

            // Length of the file:
            int length;

            // Total bytes to read:
            long dataToRead;

            // Identify the file to download including its path.
            string filepath = strDownFileName;

            // Identify the file name.
            //string  filename  = System.IO.Path.GetFileName(filepath);

            try
            {
                // Open the file.
                iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                            System.IO.FileAccess.Read, System.IO.FileShare.Read);


                // Total bytes to read:
                dataToRead = iStream.Length;

                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Utils.UrlEncode(NewFileName));

                // Read the bytes.
                while (dataToRead > 0)
                {
                    // Verify that the client is connected.
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        // Read the data in buffer.
                        length = iStream.Read(buffer, 0, 10000);

                        // Write the data to the current output stream.
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);

                        // Flush the data to the HTML output.
                        HttpContext.Current.Response.Flush();

                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        //prevent infinite loop if user disconnects
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                // Trap the error, if any.
                HttpContext.Current.Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    //Close the file.
                    iStream.Close();
                }
            }
        }
复制代码

 

posted on   悉野  阅读(319)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示