9.5文件传输.mdx 2.3 KB
Newer Older
若汝棋茗 已提交
1
---
若汝棋茗 已提交
2 3 4 5
id: httpfiletransfer
sidebar_position: 5
title: 文件传输
sidebar_label: 9.5 文件传输
若汝棋茗 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
---

## 一、说明

该Http服务器及客户端,仅仅是轻量级的Http工具,不具备广泛的兼容性,所以请慎重使用。


## 二、服务器响应文件

该操作支持大型文件,也支持断点续传、支持迅雷加速等。

```csharp
internal class MyHttpPlug : HttpPluginBase
{
    protected override void OnGet(ITcpClientBase client, HttpContextEventArgs e)
    {
        if (e.Context.Request.UrlEquals("/file"))
        {
            e.Context.Response
                .SetStatus()//必须要有状态
                .FromFile(@"D:\System\Windows.iso", e.Context.Request);//直接回应文件。
        }
        base.OnGet(client, e);
    }
}

```

## 三、服务器接收上传文件

该操作目前仅支持小文件上传,实测100Mb没问题。

```csharp
internal class MyHttpPlug : HttpPluginBase
{
    protected override void OnPost(ITcpClientBase client, HttpContextEventArgs e)
    {
        if (e.Context.Request.UrlEquals("/uploadfile"))
        {
            try
            {
                if (e.Context.Request.ContentLen>1024*1024*100)//全部数据体超过100Mb则直接拒绝接收。
                {
                    e.Context.Response
                        .SetStatus("403", "数据过大")
                        .Answer();
                    return;
                }
                //此操作会先接收全部数据,然后再分割数据。
                //所以上传文件不宜过大,不然会内存溢出。
                var multifileCollection = e.Context.Request.GetMultifileCollection();

                foreach (var item in multifileCollection)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.Append($"文件名={item.FileName}\t");
                    stringBuilder.Append($"数据长度={item.Length}");
                    client.Logger.Info(stringBuilder.ToString());
                }

                e.Context.Response
                        .SetStatus()
                        .FromText("Ok")
                        .Answer();
            }
            catch (Exception ex)
            {
                client.Logger.Exception(ex);
            }
        }
        base.OnPost(client, e);
    }
}

```