• 下载文件的方法


    /// <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();
        }
    }
  • 相关阅读:
    103、服务器出现大量close_wait的连接的原因是什么?有什么解决方法?
    102、常见的HTTP状态码有哪些?
    rpm包管理、yum源及创建本地仓库(同步华为源)
    文件管理之:输出与重定向echo
    高级权限--acl, mask,文件属性权限;su切换用户,sudo提权
    基本权限;权限对⽂件or⽬录的意义;特殊权限;文件权限之umask
    权限管理--用户介绍;用户与组相关文件;用户管理命令之用户创建、查看、删除、修改
    文件管理之:打包、压缩
    字符处理命令-sort排序,uniq去重,cut剪切文件,tr删除或替换结果集,wc统计
    上传与下载wget、curl、r z、s z
  • 原文地址:https://www.cnblogs.com/skyshenwei/p/1660152.html
Copyright © 2020-2023  润新知