如何从 Controller post 表单数据 IFormFile 到 API?
How to post form-data IFormFile to API from Controller?
在 api IFormFile 中收到空值。
Javascript:
var archivo = _('inputCargar').files[0];
const form = new FormData();
form.append("files", archivo);
const config = {
headers: {
'content-type': 'multipart/form-data'}}
await axios.post(`${data.urlUtil}Insert_FileAzure`, form, config);
表单文件到达控制器但无法到达api
前面的控制器:
public async Task<JsonResult> Insert_FileAzure([FromForm] ICollection<IFormFile> files)
{
var result = await _apiUtil.PostAsync<ICollection<IFormFile>> ("File/UploadAzure", files);
return Json(result);
}
API:
[HttpPost]
public async Task<ActionResult<RespuestaUpload>> UploadAzure([FromForm(Name = "files")] ICollection<IFormFile> files)
{
if (files == null || files.Count == 0)
return Content("file not selected");
var respuestaUpload = await _utiles.UploadFilesAzure(files);
return Ok(respuestaUpload);
}
使用 MultipartFormDataContent
作为 httpContent,如下所示:
var Client = new HttpClient();
var multipartFormDataContent = new MultipartFormDataContent();
foreach (IFormFile file in files)
{
byte[] fileData;
using (var reader = new BinaryReader(file.OpenReadStream()))
{
fileData = reader.ReadBytes((int)file.OpenReadStream().Length);
}
var fileContent = new ByteArrayContent(fileData);
multipartFormDataContent.Add(fileContent, "files", file.FileName);
}
var response = await Client.PostAsync(requestUrl, multipartFormDataContent);
在 api IFormFile 中收到空值。
Javascript:
var archivo = _('inputCargar').files[0];
const form = new FormData();
form.append("files", archivo);
const config = {
headers: {
'content-type': 'multipart/form-data'}}
await axios.post(`${data.urlUtil}Insert_FileAzure`, form, config);
表单文件到达控制器但无法到达api 前面的控制器:
public async Task<JsonResult> Insert_FileAzure([FromForm] ICollection<IFormFile> files)
{
var result = await _apiUtil.PostAsync<ICollection<IFormFile>> ("File/UploadAzure", files);
return Json(result);
}
API:
[HttpPost]
public async Task<ActionResult<RespuestaUpload>> UploadAzure([FromForm(Name = "files")] ICollection<IFormFile> files)
{
if (files == null || files.Count == 0)
return Content("file not selected");
var respuestaUpload = await _utiles.UploadFilesAzure(files);
return Ok(respuestaUpload);
}
使用 MultipartFormDataContent
作为 httpContent,如下所示:
var Client = new HttpClient();
var multipartFormDataContent = new MultipartFormDataContent();
foreach (IFormFile file in files)
{
byte[] fileData;
using (var reader = new BinaryReader(file.OpenReadStream()))
{
fileData = reader.ReadBytes((int)file.OpenReadStream().Length);
}
var fileContent = new ByteArrayContent(fileData);
multipartFormDataContent.Add(fileContent, "files", file.FileName);
}
var response = await Client.PostAsync(requestUrl, multipartFormDataContent);