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

  • 相关阅读:
    servlet中如何实现通过Spring实现对象的注入
    异步Socket
    JAVA NIO实现
    【Java并发】
    JAVA实现阻塞队列
    lock与synchronized比较
    线程执行顺序
    ConcurrentHashMap 1.8
    LeetCode 416 分割等和子集
    linux常用指令
  • 原文地址:https://www.cnblogs.com/TianFang/p/610709.html
Copyright © 2011-2022 走看看