我创建了一个以文件为参数的端点:
[HttpPost("[action]")]
[Consumes("multipart/form-data")]
public ActionResult UploadImage(IFormFile Files, string param)
{
long size = Files.Length;
var tempPath = Path.GetTempFileName();
string file_Extension = Path.GetExtension(Files.FileName);
var isValidFile = FileValidation.FileUploadValidation(Files);
if (isValidFile.data)
{
string filename = Guid.NewGuid() + "" + file_Extension;
return null;
}
else
{
return null;
}
}
我无法毫无问题地检索文件。 如何在同一方法中添加更多文本参数?
答案 0 :(得分:4)
它可以100%工作。经过测试。请执行以下步骤:
您应该为模型创建一个自定义类
public class FileInputModel
{
public string Name { get; set; }
public IFormFile FileToUpload { get; set; }
}
和类似的形式
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="UploadFileViaModel" >
<input name="Name" class="form-control" />
<input name="FileToUpload" type="file" class="form-control" />
<input type="submit" value="Create" class="btn btn-default" />
</form>
和类似的控制器方法
[HttpPost]
public async Task<IActionResult> UploadFileViaModel([FromForm] FileInputModel model)
{
if (model == null || model.FileToUpload == null || model.FileToUpload.Length == 0)
return Content("file not selected");
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", model.FileToUpload.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await model.FileToUpload.CopyToAsync(stream);
}
return RedirectToAction("Files");
}
答案 1 :(得分:2)
[HttpPost("[action]")]
[Consumes("multipart/form-data")]
public IActionResult UploadImage([FromForm] FileInputModel Files)
{
return Ok();
}
public class FileInputModel
{
public IFormFile File { get; set; }
public string Param { get; set; }
}
在添加[FromForm]
代码之后,需要在参数模型之前添加[FromForm]
才能正常工作。
答案 2 :(得分:1)
我使用以下代码进行了测试,并且可以正常工作:
public class TestController : Controller
{
[HttpPost("[controller]/[action]")]
public IActionResult Upload(Model model)
{
return Ok();
}
public class Model
{
public IFormFile File { get; set; }
public string Param { get; set; }
}
}
请注意,您需要使用模型。
以下是具有相同属性的邮递员屏幕截图。
更新:多个文件:
将模型更改为:
public class Model
{
public List<IFormFile> Files { get; set; }
public string Param { get; set; }
}
更新2
内容类型标题为multipart/form-data
以下是其工作的屏幕截图:
答案 3 :(得分:1)
C#.NET Core
[HttpPost("someId/{someId}/someString/{someString}")]
[ProducesResponseType(typeof(List<SomeResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(typeof(Dictionary<string, string[]>), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Post(int someId, string someString, [FromForm] IList<IFormFile> files)
{
...
}
打字稿:
create(someId: number, someString: string, files: File[]) {
var url = `${this.getBaseUrl()}/someId/${someId}/someString/${someString}`;
const form = new FormData();
for (let file of files) {
form.append("files", file);
}
return this.http.post<SomeResponse>(url, form, {
reportProgress: true,
});
}