【发布时间】:2021-06-04 08:56:12
【问题描述】:
我想通过流将文件上传到我的 ASP.NET 核心 API 服务器,在我将查询字符串添加到我的 POST 之前,一切正常,在这种情况下,我没有收到异常,但文件是在服务器上创建的但没有字节流入。我正在使用 Streams,因为我有非常大的文件 (20mb-8gb)
ASP.NET API:
[Route("api/[controller]")]
[ApiController]
public class UploadTestController : ControllerBase
{
// POST api/<UploadTestController>
[DisableRequestSizeLimit]
[HttpPost]
public async Task<IActionResult> Post([FromQuery]string username)
{
using (Stream stream = Request.Body)
{
try
{
using (var fstream = System.IO.File.OpenWrite(@"F:\TMP\file..."))
{
await stream.CopyToAsync(fstream);
}
return Ok("test");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return BadRequest();
}
}
}
}
客户:
class Program
{
static void Main(string[] args)
{
Upload().Wait();
}
public static async Task Upload()
{
FileStream stream = new FileStream(@"C:\TEMP\file...", FileMode.Open);
ThrottledStream throttledStream = new ThrottledStream(stream,900000);
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromMinutes(10);
var content = new MultipartFormDataContent();
content.Add(new StreamContent(throttledStream), "file...");
try
{
HttpResponseMessage response =
await client.PostAsync("https://localhost:5001/api/uploadtest?username=test", content);
var cont = await response.Content.ReadAsStringAsync();
Console.WriteLine(cont);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
}
所以如果我删除查询一切正常。我无法对自己解释这一点,因为查询不应该打扰到这一点,对吧?
【问题讨论】:
-
您使用的是哪个 ASP.net Core 版本?可能和这个有关:github.com/dotnet/aspnetcore/issues/10503
-
@FranciscoTena 我正在使用 ASP.Net Core 3.1。不幸的是,这对我没有帮助
-
什么是ThrottledStream?当我不得不处理非常大的文件时,我使用了可恢复的上传/下载库(如 Tus)
-
@FranciscoTena ThrottledStream 是用于限制上传速度的自定义流,但您也可以使用普通 FileStream。结果是一样的。
-
你可以尝试使用 var userName = new StringContent("test");内容。添加(用户名,“用户名”);而不是传入网址?
标签: c# asp.net-core dotnet-httpclient