通过ASP.NET Web Api C#中的流发送和接收大文件 [英] Send and receive large file over streams in ASP.NET Web Api C#

查看:176
本文介绍了通过ASP.NET Web Api C#中的流发送和接收大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,我需要通过流将大型音频文件从客户端发送到服务器.我正在使用ASP.NET Web Api在客户端和服务器之间进行通信.我的客户端有一个"SendFile"方法,我认为它可以正常工作,但是我不知道如何使服务器接收通过流发送的数据.到目前为止,我的客户代码看起来像这样:

I'm working on a project where I need to send large audio files via streams from a client to a server. I'm using the ASP.NET Web Api to communicate between client and server. My client has a "SendFile" method which I believe works fine, but I don't know how to make my server receive the data I'm sending via a stream. My client code looks like this so far:

 private const int MAX_CHUNK_SIZE = (1024 * 5000);
    private HttpWebRequest webRequest = null;
    private FileStream fileReader = null;
    private Stream requestStream = null;

    public bool SendAudio(string uri, string file)
    {
        byte[] fileData;
        fileReader = new FileStream(file, FileMode.Open, FileAccess.Read);
        webRequest = (HttpWebRequest)WebRequest.Create(uri);
        webRequest.Method = "POST";
        webRequest.ContentLength = fileReader.Length;
        webRequest.Timeout = 600000;
        webRequest.Credentials = CredentialCache.DefaultCredentials;
        webRequest.AllowWriteStreamBuffering = false;
        requestStream = webRequest.GetRequestStream();

        long fileSize = fileReader.Length;
        long remainingBytes = fileSize;
        int numberOfBytesRead = 0, done = 0;

        while (numberOfBytesRead < fileSize)
        {
            SetByteArray(out fileData, remainingBytes);
            done = WriteFileToStream(fileData, requestStream);
            numberOfBytesRead += done;
            remainingBytes -= done;
        }
        fileReader.Close();
        return true;
    }

    public int WriteFileToStream(byte[] fileData, Stream requestStream)
    {
        int done = fileReader.Read(fileData, 0, fileData.Length);
        requestStream.Write(fileData, 0, fileData.Length);

        return done;
    }

    private void SetByteArray(out byte[] fileData, long bytesLeft)
    {
        fileData = bytesLeft < MAX_CHUNK_SIZE ? new byte[bytesLeft] : new byte[MAX_CHUNK_SIZE];
    }

我的服务器如下:

    [HttpPost]
    [ActionName("AddAudio")]
    public async Task<IHttpActionResult> AddAudio([FromUri]string name)
    {
        try
        {
            isReceivingFile = true;
            byte[] receivedBytes = await Request.Content.ReadAsByteArrayAsync();
            if (WriteAudio(receivedBytes, name) == true)
            {
                isReceivingFile = false;
                return Ok();
            }
            else
            {
                isReceivingFile = false;
                return BadRequest("ERROR: Audio could not be saved on server.");
            }
        }
        catch (Exception ex)
        {
            isReceivingFile = false;
            return BadRequest("ERROR: Audio could not be saved on server.");
        }
    }

    public bool WriteAudio(byte[] receivedBytes, string fileName)
    {
        string file = Path.Combine(@"C:\Users\username\Desktop\UploadedFiles", fileName);
        using (FileStream fs = File.Create(file))
        {
            fs.Write(receivedBytes, 0, receivedBytes.Length);
        }
        return true;
    }

在决定尝试使其与流一起使用之前,服务器代码具有我为其编写的原始代码.如果我发送一个小文件(小于30 MB),服务器代码仍然可以工作,但是如果我发送一个大文件,我的服务器将收到"outofmemoryexception".我不知道如何使服务器通过流接收数据.在寻找解决方案的过程中,我遇到了很多有关套接字和TCPClient的示例,但这并不是我们想要在此项目中进行的.有人可以帮忙吗?

The server code has the original code I wrote for it, before deciding to try and make it work with streams. The server code still works if I send a small file (under 30 MB), but if I send a large file my server gets a "outofmemoryexception". I can't figure out how to make the server take in the data via a stream. In my search for solutions I've come across a lot of examples with sockets and TCPClient, but that's not how we want to do it on this project. Can anybody help, please?

推荐答案

如果我发送一个大文件,我的服务器将收到内存不足异常"

if I send a large file my server gets a "outofmemoryexception"

好吧,它正在将整个流读入内存:

Well, it's reading the entire stream into memory right here:

byte[] receivedBytes = await Request.Content.ReadAsByteArrayAsync();

您想要做的是将流从一个位置复制到另一个位置,立即将其全部加载到内存中.这样的事情应该起作用:

What you want to do is copy the stream from one location to another, without loading it all into memory at once. Something like this should work:

[HttpPost]
[ActionName("AddAudio")]
public async Task<IHttpActionResult> AddAudio([FromUri]string name)
{
  try
  {
    string file = Path.Combine(@"C:\Users\username\Desktop\UploadedFiles", fileName);
    using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write,
        FileShare.None, 4096, useAsync: true))
    {
      await Request.Context.CopyToAsync(fs);
    }
    return Ok();
  }
  catch (Exception ex)
  {
    return BadRequest("ERROR: Audio could not be saved on server.");
  }
}

这篇关于通过ASP.NET Web Api C#中的流发送和接收大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆