首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >客户机/服务器发送大文件

客户机/服务器发送大文件
EN

Stack Overflow用户
提问于 2015-11-16 14:31:11
回答 1查看 2.6K关注 0票数 2

我即将编写一个服务器应用程序,它应该能够从多个来源接收大型文件(与所有其他FTP客户机/服务器应用程序一样安静)。

但我不知道什么是最好的方法,需要一些建议。

客户端将向服务器发送XML数据,服务器看起来如下所示:

代码语言:javascript
运行
复制
<Data xmlns="http://schemas.datacontract.org/2004/07/DataFiles" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Category>General</Category>
    <Files>
        <DataFile>
            <Extension>.txt</Extension>
            <Filename>test4</Filename>
            <Bytes>"Some binary data"</Bytes>
        </DataFile>
    </Files>
</Data>

首先,我创建了一个HTTPListener作为我的服务器,但是在服务器端的大型文件上,它似乎遇到了很多困难(基本上是因为上下文是作为一个数据包而不是分段的)接收的,而且当服务器确实反序列化接收到的XML数据时,它会将其加载到内存中,这对于大文件来说是不可取的。

然后,我转到一个TcpListener,使其更低一层,这在大型文件上似乎很好,因为它们被发送成碎片,但是当收到请求时,我需要做大量的工作来在服务器端追加包。

作为一种可能,我也很快就转移到了WCF上,但是我对这一技术缺乏经验,这使我再次离开了这种方法。

您会做什么?,您将使用.NET工具箱中的哪个.NET工具来创建FTP服务器/客户端?

关于TcpListeners等有很多线程,这不是我在这里寻找的。我需要关于我应该采用的方法和最佳实践的建议。

编辑:忘记提到它背后的想法更像是一个FTP代理(客户端发送文件到服务器>服务器存储文件本地>服务器将它发送到第三部分位置>服务器在成功完成seding文件到第三方位置时清除本地存储的文件)。

编辑17-11-15:

下面是我如何做HTTP服务器的示例代码:

代码语言:javascript
运行
复制
public class HttpServer
{
    protected readonly HttpListener HttpListener = new HttpListener();

    protected HttpServer(IEnumerable<string> prefixes)
    {
        HttpListener.Prefixes.Add(prefix);
    }

    public void Start()
    {
        while (HttpListener.IsListening && Running)
        {
            var result = HttpListener.BeginGetContext(ContextReceived, HttpListener);
            if (WaitHandle.WaitAny(new[] {result.AsyncWaitHandle, _shutdown}) == 0)
                return;
        }
    }

    protected object ReadRequest(HttpListenerRequest request)
    {
        using (var input = request.InputStream)
        using (var reader = new StreamReader(input, request.ContentEncoding))
        {
            var data = reader.ReadToEnd();
            return data;
        }
    }

    protected void ContextReceived(IAsyncResult ar)
    {
        HttpListenerContext context = null;
        HttpListenerResponse response = null;
        try
        {
            var listener = ar.AsyncState as HttpListener;
            if (listener == null) throw new InvalidCastException("ar");
            context = listener.EndGetContext(ar);
            response = context.Response;
            switch (context.Request.HttpMethod)
            {
                case WebRequestMethods.Http.Post:
                    // Parsing XML data with file at LARGE byte[] as one of the parameter, seems to struggle here...
                    break;
                default:
                    //Send MethodNotAllowed response..
                    break;
            }
            response.Close();
        }
        catch(Exception ex)
        {
            //Do some properly exception handling!!
        }
        finally
        {
            if (context != null)
            {
                context.Response.Close();
            }
            if (response != null)
                response.Close();
        }
    }
}

客户端正在使用:

代码语言:javascript
运行
复制
using (var client = new WebClient())
{
    GetExtensionHeaders(client.Headers);
    client.Encoding = Encoding.UTF8;
    client.UploadFileAsync(host, fileDialog.FileName ?? "Test");
    client.UploadFileCompleted += ClientOnUploadFileCompleted;
    client.UploadProgressChanged += ClientOnUploadProgressChanged;
}

请注意,客户端应该将数据(作为XML)发送到服务器,这将反序列化接收到的数据(使用filestream服务器端),如前面所写。

下面是我的TcpServer示例:

代码语言:javascript
运行
复制
public class TcpServer
{
    protected TcpListener Listener;
    private bool _running;

    public TcpServer(int port)
    {
        Listener = new TcpListener(IPAddress.Any, port);
        Console.WriteLine("Listener started @ {0}:{1}", ((IPEndPoint)Listener.LocalEndpoint).Address, ((IPEndPoint)Listener.LocalEndpoint).Port);
        _running = true;
    }

    protected readonly ManualResetEvent TcpClientConnected = new ManualResetEvent(false);
    public void Start()
    {
        while (_running)
        {
            TcpClientConnected.Reset();
            Listener.BeginAcceptTcpClient(AcceptTcpClientCallback, Listener);
            TcpClientConnected.WaitOne(TimeSpan.FromSeconds(5));
        }
    }

    protected void AcceptTcpClientCallback(IAsyncResult ar)
    {
        try
        {
            var listener = ar.AsyncState as TcpListener;
            if (listener == null) return;

            using (var client = listener.EndAcceptTcpClient(ar))
            {
                using (var stream = client.GetStream())
                {
                    //Append or create to file stream
                }
            }

            //Parse XML data received?
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            TcpClientConnected.Set();
        }
    }
}   
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-16 15:25:31

创建一个新的空MVC应用程序

接下来,向Controllers文件夹中添加一个新控制器,

代码语言:javascript
运行
复制
using System.Web;
using System.Web.Mvc;

namespace UploadExample.Controllers
{
    public class UploadController : Controller
    {
        public ActionResult File(HttpPostedFileBase file)
        {
            file.SaveAs(@"c:\FilePath\" + file.FileName);
        }

    }
}

现在你要做的就是上传一个文件,把它作为多部分的表单数据发布到你的网站上.

代码语言:javascript
运行
复制
void Main()
{   
    string fileName = @"C:\Test\image.jpg";
    string uri = @"http://localhost/Upload/File";
    string contentType = "image/jpeg";

    Http.Upload(uri, fileName, contentType);
}

public static class Http
{
    public static void Upload(string uri, string filePath, string contentType)
    {
        string boundary         = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundaryBytes    = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

        string formdataTemplate = "Content-Disposition: form-data; name=file; filename=\"{0}\";\r\nContent-Type: {1}\r\n\r\n";
        string formitem         = string.Format(formdataTemplate, Path.GetFileName(filePath), contentType);
        byte[] formBytes        = Encoding.UTF8.GetBytes(formitem);

        HttpWebRequest request  = (HttpWebRequest) WebRequest.Create(uri);
        request.KeepAlive       = true;
        request.Method          = "POST";
        request.ContentType     = "multipart/form-data; boundary=" + boundary;
        request.SendChunked     = true;

        using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            requestStream.Write(formBytes, 0, formBytes.Length);

            byte[] buffer = new byte[1024*4];
            int bytesLeft;

            while ((bytesLeft = fileStream.Read(buffer, 0, buffer.Length)) > 0) requestStream.Write(buffer, 0, bytesLeft);

            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
        }

        using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
        {
        }

        Console.WriteLine ("Success");    
    }
}

编辑

如果遇到问题,编辑Web.Config文件,很可能达到了请求长度限制.

代码语言:javascript
运行
复制
<system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"  maxRequestLength="1048576"/>
</system.web>

我遗漏的另一件事(但现在编辑了)是发送块属性在webrequest上的自身。

代码语言:javascript
运行
复制
request.SendChunked = true;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33737790

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档