zoukankan      html  css  js  c++  java
  • 用HttpListener实现文件下载

    和asp.net中一样,如果要实现url重定向,使用response.Redirect()方法即可,在中使用如下:

    string desUrl = "http://www.google.com";
    response.Redirect(desUrl);
    response.OutputStream.Close();

    如果desUrl执行的是网络上的一个文件,一般ie就会提示文件下载。但是,许多时候,ie会打开这个文件(如目标是文本文件就会这样),这有时不是我们所需要的,如何强制ie以下载的方式获取文件呢?解决方式如下:

    static void ProcessHttpClient(object obj)
    {
        HttpListenerContext context = obj as HttpListenerContext;
        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;

        response.ContentType = "application/octet-stream";

        string fileName = "time.txt";
        response.AddHeader("Content-Disposition", "attachment;FileName=" + fileName);

        byte[] data = Encoding.Default.GetBytes(string.Format("
    当前时间: {0}", DateTime.Now));
        response.ContentLength64 = data.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(data, 0, data.Length);
        output.Close();
    }

    这种方式有一个小问题,那就是当文件名为中文时,会产生乱码,解决方法是用调用HttpUtility.UrlEncode 函数对文件名进行编码。

  • 相关阅读:
    Python: 通过 pip 安装第三方包后依然不能 import
    jar命令
    vim中删除^M
    Linux 非互联网环境安装依赖包
    安装rpm包时提示错误:依赖检测失败的解决方法
    python3.5安装
    yum配置安装 及报错
    统计数组元素出现的次数
    插入法排序
    选择法排序
  • 原文地址:https://www.cnblogs.com/TianFang/p/610709.html
Copyright © 2011-2022 走看看