我正在编写一个 asp .net 6 程序,它接收许多文件并将它们写入 sqlite 数据库。
我在客户端使用以下代码来发送文件:
var request = new HttpRequestMessage() {
Method = HttpMethod.Post,
RequestUri = new Uri(server.serverBase + "/api/snapshot/UploadFile"),
};
using (FileStream filestream = File.Open(file.getFilePath(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
var length = filestream.Length.ToString();
var streamContent = new StreamContent(filestream, 16384);
streamContent.Headers.Add("Content-Type", "application/octet-stream");
streamContent.Headers.Add("Content-Length", length);
request.Content = streamContent;
var httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 2, 0);
var response = httpClient.SendAsync(request).Result;
//Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
在服务器上使用以下代码来接收流:
[HttpPost("UploadFile")]
[RequestSizeLimit(100000000000)]
public async Task<IActionResult> UploadFile()
{
int CHUNK_SIZE = 1024 * 1024; //1 MB chunk size
using (Stream stream = HttpContext.Request.Body) {
var buffer = new byte[CHUNK_SIZE];
int bytesRead;
int chunkNumber = 0;
long totalNumBytes = 0;
int progress = 0;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) {
System.Diagnostics.Debug.WriteLine(bytesRead);
await ProcessChunk(buffer, bytesRead, chunkNumber, totalNumBytes);
chunkNumber++;
}
}
return Ok("File uploaded and chunked successfully.");
}
但是,尽管缓冲区大小为 1048576 字节,调试输出始终为 4096,即,我只读取流的每个“块”4096 字节。
如何将缓冲区大小增加到 4096 字节以上?
我的最终目标是获取每个“块”并将其作为 blob 存储到数据库中,发送的大多数文件约为 3KB,因此我打算更改每个“块”大小,即 1KB,以便每个块使用更少的行文件块。
我已经尝试过:
我预计 HttpContext.Request.Body 的流缓冲区会增加到超过 4096 字节,但似乎我无法让它超过该值。
您需要增加 web.config 中的 maxAllowedContentLength
<configuration>
<system.webServer>
<security>
<requestFiltering removeServerHeader="true">
<requestLimits maxAllowedContentLength="2147483647" />