在 ASP.NET Web Api C# 中通过流发送和接收大文件

编程入门 行业动态 更新时间:2024-10-23 01:48:13
本文介绍了在 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]; }

我的服务器看起来像这样:

My server looks like this:

[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:UsersusernameDesktopUploadedFiles", 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?

推荐答案

如果我发送一个大文件,我的服务器会收到outofmemoryexception"

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:UsersusernameDesktopUploadedFiles", 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# 中通过流发送和接收大文件

本文发布于:2023-11-25 17:37:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630704.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:大文件   过流   NET   ASP   Api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!