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();}}}}
}