我正在尝试在 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。
当我调试代码时,出现以下错误。
最佳答案
一个解决方案是您可以使用 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/