作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如标题所示,我正在尝试将 .zip 从我的 WPF 应用程序上传到我的 .NET Core Web API。
经过一些研究,我发现可以使用 MultiPartDataContent 并以这种方式发送它。
向服务器发送数据的代码如下所示:
{
client.BaseAddress = new Uri("http://localhost:62337/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string filepath = @"C:\Users\uic10950\Desktop\Meeting2Text\RecordingApp\bin\mixedaudio.zip";
string filename = "mixedaudio.zip";
MultipartFormDataContent content = new MultipartFormDataContent();
ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
content.Add(fileContent);
HttpResponseMessage response = await client.PostAsync("api/transcriptions/recording", content);
string returnString = await response.Content.ReadAsAsync<string>();
}
在服务器端,我的 Controller 操作如下所示:
public async Task<IActionResult> AddFileToTranscription([FromForm] IFormFile file)
{
using (var sr = new StreamReader(file.OpenReadStream()))
{
var content = await sr.ReadToEndAsync();
return Ok(content);
}
}
此操作代码将在文件上传工作后立即更改
根据我在研究过程中的理解,我的文件应该位于:
[FromForm] IFormFile
Action 的文件属性,可惜为空。
最佳答案
你做错了几件事:
public async Task<IActionResult> AddFileToTranscription([FromForm] IFormFile file)
❌ 你不需要 [FromFile]
属性。
❌ 你的文件参数名称是 file
但你在客户端上传文件时没有定义它。
❌ 您不需要添加 ContentDisposition
并将其设置为 attachment
因为它用于响应,而不是请求! (1)
✅ 服务器:
public async Task<IActionResult> AddFileToTranscription( IFormFile file)
{
using (var sr = new StreamReader(file.OpenReadStream()))
{
var content = await sr.ReadToEndAsync();
return Ok(content);
}
}
✅ 客户:
client.BaseAddress = new Uri("http://localhost:62337/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string filepath = @"C:\Users\uic10950\Desktop\Meeting2Text\RecordingApp\bin\mixedaudio.zip";
string filename = "mixedaudio.zip";
MultipartFormDataContent content = new MultipartFormDataContent();
ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));
// ➡ ✅ important change fileContent, form-input-name, real-file-name
content.Add(fileContent, "file", filename);
HttpResponseMessage response = await client.PostAsync("api/transcriptions/recording", content);
string returnString = await response.Content.ReadAsAsync<string>();
MultipartFormDataContent.Add
方法有几个用于添加表单数据的重载,您必须使用此 overload :
public void Add (System.Net.Http.HttpContent content, string name, string fileName);
结论:
无论您的 IFormData
参数是什么,您都需要使用该名称上传或发送请求!
关于c# - 使用 HttpClient 将 Zip 文件上传到 ASP.NET Core Web API 服务,但 FormData 参数始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56847199/
我是一名优秀的程序员,十分优秀!