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 函数对文件名进行编码。

  • 相关阅读:
    Jmeter(七)Jmeter脚本优化(数据与脚本分离)
    Jmeter(六)Jmeter脚本包含要素及书写习惯
    Redis的持久化之AOF方式
    Redis的持久化之RDB方式
    Redis持久化介绍
    Redis Keys的通用操作
    Redis的数据结构之sorted-set
    Redis的数据结构之哈希
    Redis的数据结构之字符串
    Jedis 连接池实例
  • 原文地址:https://www.cnblogs.com/TianFang/p/610709.html
Copyright © 2011-2022 走看看