当前位置: 首页 > article >正文

C# HttpListener 实现的HTTP Sever浏览器文件下载

 1. 前端页面请求

编写简单的test.html 文件,body体值配置a标签,其href 属性设置为文件下载请求的http接口要求的参数序列。

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>文件下载测试</title>
</head>

<body>
    <a href='http://localhost:8080/133419272086_1_1724083200_1724169600.mp4?MediaType=0&StreamType=0&StorageType=1&PlaybackMode=0&Multiple=1&DataSource=0&Speed=4&CTags=null' target='_blank'>文件下载</a>

</body>
</html>

浏览器打开如下:

发起请求,点击“文件下载”链接即可。

 2.后端响应处理

前端使用http接口发起请求,相当于客户端,因此后端需要开发服务端。使用C#开发后端响应处理程序。在C#中使用HttpServer,可以通过.Net Framework提供的HttpListener类来实现Http Server。具体代码实现如下:

1)创建服务端,开始监听

            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:8080/"); // 设置HttpServer监听的地址和端口号

            listener.Start();

2)设置服务端响应文件内容类型,及文件

                HttpListenerResponse lsresponse = context.Response;
                //设置内容类型
                lsresponse.ContentType = "application/octet-stream";

                //准备文件路径
                string filePath = "./133419272086_1_1724083200_1724169600.mp4";

3)复制文件到响应流

                    //准备文件流
                    using (FileStream fs = File.OpenRead(filePath))
                    {
                        // 复制文件到响应流
                        await fs.CopyToAsync(lsresponse.OutputStream);
                        Console.WriteLine($"Sending: {filePath}");
                    }

3.测试

浏览器打开test.html,点击按钮“文件下载”

完整代码如下:

using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http;

namespace HttpServerDemo
{
    class Program
    {
        static async Task Main(string[] args)
        {
Console.WriteLine("File Down Demo test.");
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:8080/"); // 设置HttpServer监听的地址和端口号

            listener.Start();

            Console.WriteLine("HttpServer started. Listening...");

            while (true)
            {
                HttpListenerContext context = await listener.GetContextAsync(); // 接收来自客户端的请求
                HttpListenerRequest request = context.Request;

                Console.WriteLine("Request received: " + request.ContentType + " " + request.HttpMethod + " " + request.Url);

                HttpListenerResponse lsresponse = context.Response;
                //设置内容类型
                lsresponse.ContentType = "application/octet-stream";

                //准备文件路径
                string filePath = "./133419272086_1_1724083200_1724169600.mp4";

                try
                {
                    //准备文件流
                    using (FileStream fs = File.OpenRead(filePath))
                    {
                        // 复制文件到响应流
                        await fs.CopyToAsync(lsresponse.OutputStream);
                        Console.WriteLine($"Sending: {filePath}");
                    }
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    lsresponse.StatusCode = 500;
                }
                finally
                {
                    lsresponse.Close();
                }
            }
        }
    }
}


http://www.kler.cn/news/310579.html

相关文章:

  • 配电房监控 配电柜监测系统方案简介@卓振思众
  • 基于C语言--解读main(int agrc,char* argv[ ])(命令行参数+环境变量)
  • 【数据结构与算法】排序算法之快速排序(简)
  • WPF自定义Dialog模板,内容用不同的Page填充
  • TypeScript入门 (二)控制语句
  • C++伟大发明--模版
  • 使用大语言模型(LLM)修正小段乱码(Mojibake)为正常文本
  • expected_conditions(EC) 判断元素的操作
  • OpenCVSharp直方图和傅里叶变换介绍
  • 2024.9.15 Python模式识别新国大EE5907,总结PCA,LDA,Clustering,GMMboosting,SVM
  • istio中serviceentry结合egressgateway的使用
  • 求和(2)
  • C# 禁止程序重复启动
  • 科技创新驱动未来发展
  • Qt 内嵌 Python 解释器动态调试
  • canvas和svg的区别是什么?它们的应用场景是什么?
  • github域名与IP变更导致无法推送分支问题的解决
  • QT信号槽原理是什么,如何去使用它?
  • POSIX信号量以及利用POSIX信号量实现基于循环队列的高效生产者消费者模型
  • 【iOS】dismiss多级的方法
  • 《A++ 敏捷开发》- 26 根与翼
  • 如何使用自动化测试工具来提高API测试的效率?
  • html详细知识
  • Android中的单例模式
  • 怎么给儿童掏耳朵比较安全?安全儿童可视挖耳勺推荐
  • 价值、创新、社区与财富效应:Match项目的成功启示
  • 【网络安全】PHP配置注入漏洞
  • php环境搭建教程
  • float字节序和主机序 网络序传输
  • 优化算法(三)—模拟退火算法(附MATLAB程序)