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();
        }
    }
  • 相关阅读:
    情书2
    情书1
    python_数据分析_正态分布
    python3调用R语言干货
    常见混淆名词
    PID算法图形 python
    A*寻路算法 python实现
    用tensorflow object detection api做手势识别
    tf识别非固定长度图片ocr(数字+字母 n位长度可变)- CNN+RNN+CTC
    tf识别固定长度验证码图片ocr(0到9 4位)- CNN方式
  • 原文地址:https://www.cnblogs.com/skyshenwei/p/1660152.html
Copyright © 2011-2022 走看看