将文件请求到网络 API
Request with file to web API
应用程序将文件发送到 Web 服务时出现问题。这是我的 endpoint/controller.
[HttpPost]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
var filePath = "C:\Files\TEST.pdf";
using (var stream = System.IO.File.Create(filePath))
{
await formFile.CopyToAsync(stream);
}
}
}
这个控制器在 Postman 中工作正常。
这是我提出请求的应用程序:
byte[] bytes = System.IO.File.ReadAllBytes("C:\Files\files.pdf");
Stream fileStream = File.OpenRead("C:\Files\files.pdf");
HttpContent bytesContent = new ByteArrayContent(bytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(bytesContent,"file", "files.pdf");
try
{
var response = await client.PostAsync(url, formData);
}catch(Exception ex)
{
Console.WriteLine(ex);
}
没用。我没有在控制器中收到文件。我也试过这个:
string fileToUpload = "C:\Files\files.pdf";
using (var client = new WebClient())
{
byte[] result = client.UploadFile(url, fileToUpload);
string responseAsString = Encoding.Default.GetString(result);
}
但结果是一样的。你能帮忙吗?
2020 年 9 月 15 日更新
这是ConsoleApplication
中的上传代码。它适用于小文件但不适用于大文件。
public static async Task upload(string url)
{
//const string url = "https://localhost:44308/file/post";
const string filePath = "C:\Files\files.pdf";
try {
using (var httpClient = new HttpClient{
Timeout = TimeSpan.FromSeconds(3600)
})
{
using (var form = new MultipartFormDataContent())
{
using (var fs = System.IO.File.OpenRead(filePath))
{
fs.Position = 0;
using (var streamContent = new StreamContent(fs))
{
form.Add(streamContent, "files", Path.GetFileName(filePath));
HttpResponseMessage response = httpClient.PostAsync(url, form).Result;
fs.Close();
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
有两个步骤可以解决您的问题。
1.Add ContentType 到 Headers
bytesContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
2。 formData 中的文件参数名称应与操作参数名称匹配。
formData.Add(bytesContent,"file", "files.pdf"); //should be files
public async Task<IActionResult> Post(List<IFormFile> files)
更新
HttpClient.PostAsync()
在控制台应用程序中等待时不起作用。不要使用 .Result 阻塞,而是使用 .GetAwaiter().GetResult()。
HttpResponseMessage response = httpClient.PostAsync(url, form).Result;
这里是展示如何上传文件的代码。
控制器代码
public class FileController : Controller
{
[HttpPost]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
var filePath = "C:\Files\TEST.pdf";
using (var stream = System.IO.File.Create(filePath))
{
await formFile.CopyToAsync(stream);
}
}
}
return Ok();
}
[HttpGet]
public async Task<IActionResult> upload()
{
const string url = "https://localhost:44308/file/post";
const string filePath = @"C:\Files\files.pdf";
using (var httpClient = new HttpClient())
{
using (var form = new MultipartFormDataContent())
{
using (var fs = System.IO.File.OpenRead(filePath))
{
using (var streamContent = new StreamContent(fs))
{
using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()))
{
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
// "file" parameter name should be the same as the server side input parameter name
form.Add(fileContent, "files", Path.GetFileName(filePath));
HttpResponseMessage response = await httpClient.PostAsync(url, form);
}
}
}
}
}
return Ok();
}
}
测试
应用程序将文件发送到 Web 服务时出现问题。这是我的 endpoint/controller.
[HttpPost]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
var filePath = "C:\Files\TEST.pdf";
using (var stream = System.IO.File.Create(filePath))
{
await formFile.CopyToAsync(stream);
}
}
}
这个控制器在 Postman 中工作正常。
这是我提出请求的应用程序:
byte[] bytes = System.IO.File.ReadAllBytes("C:\Files\files.pdf");
Stream fileStream = File.OpenRead("C:\Files\files.pdf");
HttpContent bytesContent = new ByteArrayContent(bytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(bytesContent,"file", "files.pdf");
try
{
var response = await client.PostAsync(url, formData);
}catch(Exception ex)
{
Console.WriteLine(ex);
}
没用。我没有在控制器中收到文件。我也试过这个:
string fileToUpload = "C:\Files\files.pdf";
using (var client = new WebClient())
{
byte[] result = client.UploadFile(url, fileToUpload);
string responseAsString = Encoding.Default.GetString(result);
}
但结果是一样的。你能帮忙吗?
2020 年 9 月 15 日更新
这是ConsoleApplication
中的上传代码。它适用于小文件但不适用于大文件。
public static async Task upload(string url)
{
//const string url = "https://localhost:44308/file/post";
const string filePath = "C:\Files\files.pdf";
try {
using (var httpClient = new HttpClient{
Timeout = TimeSpan.FromSeconds(3600)
})
{
using (var form = new MultipartFormDataContent())
{
using (var fs = System.IO.File.OpenRead(filePath))
{
fs.Position = 0;
using (var streamContent = new StreamContent(fs))
{
form.Add(streamContent, "files", Path.GetFileName(filePath));
HttpResponseMessage response = httpClient.PostAsync(url, form).Result;
fs.Close();
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
有两个步骤可以解决您的问题。
1.Add ContentType 到 Headers
bytesContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
2。 formData 中的文件参数名称应与操作参数名称匹配。
formData.Add(bytesContent,"file", "files.pdf"); //should be files
public async Task<IActionResult> Post(List<IFormFile> files)
更新
HttpClient.PostAsync()
在控制台应用程序中等待时不起作用。不要使用 .Result 阻塞,而是使用 .GetAwaiter().GetResult()。
HttpResponseMessage response = httpClient.PostAsync(url, form).Result;
这里是展示如何上传文件的代码。
控制器代码
public class FileController : Controller
{
[HttpPost]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
var filePath = "C:\Files\TEST.pdf";
using (var stream = System.IO.File.Create(filePath))
{
await formFile.CopyToAsync(stream);
}
}
}
return Ok();
}
[HttpGet]
public async Task<IActionResult> upload()
{
const string url = "https://localhost:44308/file/post";
const string filePath = @"C:\Files\files.pdf";
using (var httpClient = new HttpClient())
{
using (var form = new MultipartFormDataContent())
{
using (var fs = System.IO.File.OpenRead(filePath))
{
using (var streamContent = new StreamContent(fs))
{
using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()))
{
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
// "file" parameter name should be the same as the server side input parameter name
form.Add(fileContent, "files", Path.GetFileName(filePath));
HttpResponseMessage response = await httpClient.PostAsync(url, form);
}
}
}
}
}
return Ok();
}
}