问题
What's the best way to POST both images and JSON at the same time in a single POST ? (using multipart) I have a form with some data that i put into JSON and the users can add 0 to 6 photos and submit it to the API.
Can someone explain me how to do it ?
Edit : Here is my code thanks to your help :
// POST api/<controller>
[HttpPost, Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IActionResult Post(ViewModel vm)
{
IActionResult response = Unauthorized();
var data = vm.FamilleProduit;
var reforigine = vm.RefOrigine;
if (vm.Images != null)
{
foreach (var image in vm.Images)
{
byte[] fileData = null;
// read file to byte array
using (var binaryReader = new BinaryReader(image.OpenReadStream()))
{
fileData = binaryReader.ReadBytes((int)image.Length);
}
}
}
return response;
}
public class ViewModel
{
public string FamilleProduit { get; set; }
public string RefOrigine { get; set; }
public List<IFormFile> Images { get; set; }
}
I'm testing with Postman and i POST 2 text (FamilleProduit & RefOrigine) and 2 files (2 images) with "multipart/form-data". I get the 2 texts perfectly but Images field is null everytime.
Thanks, Tristan.
回答1:
You can use built-in class IFormFile to easily work with file upload. To use it together with JSON you may create custom model binder and combine it together in DTO object:
public class ViewModel
{
[ModelBinder(BinderType = typeof(FormDataJsonBinder))]
public DataModel Data { get;set; }
public List<IFormFile> Images { get; set; }
}
public class FormDataJsonBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if(bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
string fieldName = bindingContext.FieldName;
var valueProviderResult = bindingContext.ValueProvider.GetValue(fieldName);
if(valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
else
{
bindingContext.ModelState.SetModelValue(fieldName, valueProviderResult);
}
string value = valueProviderResult.FirstValue;
if(string.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
try
{
object result = JsonConvert.DeserializeObject(value, bindingContext.ModelType);
bindingContext.Result = ModelBindingResult.Success(result);
}
catch(JsonException)
{
bindingContext.Result = ModelBindingResult.Failed();
}
return Task.CompletedTask;
}
}
Then you can work with it in your controller:
[HttpPost]
public IActionResult Create(ViewModel vm)
{
var data = vm.Data;
if (vm.Images != null)
{
foreach(var image in vm.Images)
{
byte[] fileData = null;
// read file to byte array
using (var binaryReader = new BinaryReader(image.OpenReadStream()))
{
fileData = binaryReader.ReadBytes((int)image.Length);
}
}
}
}
来源:https://stackoverflow.com/questions/51614373/multipart-form-data-images-upload-with-json-asp-net-core-api