zoukankan      html  css  js  c++  java
  • 下载文件的方法

    经常用到导出文件的功能,在导出文件后,首先文件是暂时保存在服务器上的一个临时目录中,然后调用下面的方法将文件输出到客户端供用户下载。下载完成后,并删除服务器上的临时文件。
    代码
    /// <summary>
    /// 从服务器下载文件到客户端
    /// </summary>
    /// <param name="filepath">要下载文件的绝对物理路径</param>
    public static void OutputFileToClient(string filepath)
    {
        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;
        
    //得到文件名
        string filename = System.IO.Path.GetFileName(filepath);
        
    //当前 http 上下文
        HttpContext context = HttpContext.Current;
        
    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;

            context.Response.ContentType 
    = "application/octet-stream";
            context.Response.AddHeader(
    "Content-Disposition""attachment; filename=" + filename);

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

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

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

                    buffer 
    = new Byte[10000];
                    dataToRead 
    = dataToRead - length;
                }
                
    else
                {
                    
    //prevent infinite loop if user disconnects
                    dataToRead = -1;
                }
            }
        }
        
    catch (Exception ex)
        {
            
    throw ex;
        }
        
    finally
        {
            
    if (iStream != null)
            {
                
    //Close the file.
                iStream.Close();
                
    //删除服务器上的文件
                System.IO.File.Delete(filepath);
            }
            
    //结束输出流
            context.Response.Close();
        }
    }
  • 相关阅读:
    转:[Silverlight入门系列]使用MVVM模式(9): 想在ViewModel中控制TreeView节点展开?
    C#线程同步方法——Monitor
    转:Mongodb源码分析之Replication模式
    转:Mysql使用主从复制机制(replication)
    Ruby IDE
    转:ASP.NET MVC4细嚼慢咽---(5)js css文件合并
    转:ASP.NET MVC4细嚼慢咽---(6)全局过滤器
    转:WCF服务开发与调用的完整示例
    转:WF工作流技术内幕 —— 通过Web服务调用Workflow工作流(开发持久化工作流)
    汇总高效的卷积神经网络结构[转载]
  • 原文地址:https://www.cnblogs.com/weekend001/p/1655992.html
Copyright © 2011-2022 走看看