Uploading A File Using IFormFile Should Show An Upload Button
Uploading A File Using IFormFile Should Show An Upload Button
===============
In addition, I've tried using the following IOperationFilter based on this MVC 5
Swashbuckle code without success:
=======solution========
Janak S. has provided an excellent solution for this. I believe it should produce
your desired results.
Solution
My Example:
Controller
<xmp>
public async Task UploadFile(IFormFile filePayload)
{
var fileName = ContentDispositionHeaderValue
.Parse(filePayload.ContentDisposition)
.FileName
.Trim('"');
if (filePayload.Length > 0)
using (var fileStream = new
FileStream(Path.Combine($"{_config.GetValue("FileUploadPath")}", fileName),
FileMode.Create))
await filePayload.CopyToAsync(fileStream);
return new OkObjectResult("Success");
}
</xmp>
Operation Filter
<xmp>
public class FileOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (context.ApiDescription.ParameterDescriptions.Any(x =>
x.ModelMetadata.ContainerType == typeof(IFormFile)))
{
operation.Parameters.Clear();
operation.Parameters.Add(new NonBodyParameter
{
Name = "FilePayload", // must match parameter name from
controller method
In = "formData",
Description = "Upload file.",
Required = true,
Type = "file"
});
operation.Consumes.Add("application/form-data");
}
}
}
</xmp>
Swagger config
<xmp>
services.AddSwaggerGen(c =>
{
c.OperationFilter();
});
</xmp>