asp.net-core-3.0 - 在 .Net core 3.0 控制台应用程序中使用 HttpClient 上传文件

标签 asp.net-core-3.0 .net-core-3.0

我正在尝试在 Asp.net Core 3 中使用 HttpClient 上传文件,但它没有将文件上传到服务器。如果我尝试通过 Postman 将文件上传到服务器,它会成功。

下面是我上传文件的简单代码:

HttpClient _client = new HttpClient();
var stream = new FileStream("main.txt", FileMode.Open);
byte[] fileBytes = new byte[stream.Length];
stream.Write(fileBytes, 0, (int)stream.Length);
stream.Dispose();

using (var content = new MultipartFormDataContent())
{
    var fileContent = new ByteArrayContent(fileBytes);
    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "Test",
    };
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
    content.Add(fileContent);

    _client.PostAsync("http://192.168.56.1:8000", content);                
}

正如我上面所说,它正在与 Postman 合作。我正在放一张截图,显示我如何使用 Postman。

enter image description here

enter image description here

当我调试代码时,出现以下错误。

enter image description here

最佳答案

一个解决方案是您可以使用 MemoryStream 来转换文件的内容。您的方法将导致 main.txt 文件中的内容变为空。

像这样更改您的代码:

HttpClient _client = new HttpClient();
Stream stream = new FileStream("main.txt", FileMode.Open);​ 
MemoryStream ms = new MemoryStream();​
stream.CopyTo(ms);​
byte[] fileBytes = ms.ToArray();​
ms.Dispose(); ​

另一种方法是使用 System.IO.File.ReadAllBytes(filePath)

尝试使用下面的示例代码来发布文件,引用我的 answer .

using (var client = new HttpClient())
        {
            using (var content = new MultipartFormDataContent())
            {

                //replace with your own file path, below use an txt in wwwroot for example
                string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "main.txt");

                byte[] file = System.IO.File.ReadAllBytes(filePath);

                var byteArrayContent = new ByteArrayContent(file);

                content.Add(byteArrayContent, "file", "main.txt");

                var url = "https://localhost:5001/foo/bar";
                var result = await client.PostAsync(url, content);

            }
        }

foo/bar Action

[HttpPost]
[Route("foo/bar")]
public IActionResult ProcessData([FromForm]IFormFile file)
{
     //your logic to upload file
}

关于asp.net-core-3.0 - 在 .Net core 3.0 控制台应用程序中使用 HttpClient 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60196446/

相关文章:

asp.net-core - 如何正确解析要在 ASP.NET Core 3.1 的 ConfigureServices() 中使用的服务?

azure - 使用 aspnetcore3 执行 Azure function v2 时出现异常 - 系统找不到指定的文件。系统.Private.CoreLib

.net-core - EF Core 3.0 中的 LINQ 重大更改。如何在没有收到警告 CA1308 的情况下比较字符串?

winforms - 我是否应该使用 WinForms 控件修改我的 nuget 包以便在 .NET Core 3 应用程序中使用?

c# - ASP.NET Core 3.0 - InProcess 与 OutOfProcess(HTTP 错误 500.30 - ANCM 进程内启动失败)

asp.net-core - 带有 503 服务不可用的 Asp Net Core 3 示例

authorization - MapWhen() 中的 MVC 授权应用于所有 Controller

visual-studio - Frameworks\Microsoft.AspNetCore.App 上的黄色三角形

c# - AVX2 SIMD XOR 在 .NET 中没有产生性能改进

c# - .net core 3 wpf/winforms(非 MSIX)的安装程序?