• 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();
                    }
                }
            }
  • 相关阅读:
    mysql服务的注册,启动、停止、注销。 [delphi代码实现]
    java初始化
    git的使用
    jmeter测试
    Linux上安装Redis
    java多线程
    设计模式之装饰着模式
    IO流之字符流知识总结
    IO流之字节流知识总结
    java File类
  • 原文地址:https://www.cnblogs.com/barrysgy/p/3185786.html
Copyright © 2020-2023  润新知