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

  • 相关阅读:
    debian配置apache2.4配置虚拟主机遇到的问题
    Javascript关于attachEvent和addEventListener区别与兼容写法
    图解linux下top命令的使用
    idea报错:java 不支持发行版本5
    java-访问权限
    IDEA图标含义
    IDEA生成UML类图
    idea快捷键
    idea同时运行两个main()
    idea关闭vim编辑模式
  • 原文地址:https://www.cnblogs.com/TianFang/p/610709.html
Copyright © 2011-2022 走看看