简体   繁体   中英

How to send files(IFormFile) from Web Controller Action to API Controller Action?

Let us say I want to upload some files.

My HTML Form in the Razor View looks like this:

@model SequereMe.Onboarding.Web.ViewModels.Branding.TenantBrandingViewModel
@{
}

<form asp-controller="BrandingSettings" asp-action="Save" asp-method="post" enctype="multipart/form-data">
    <div class="form-group">
        <input asp-for="TenantId" value=@Model.TenantId />
    </div>
    <div class="form-group">
        <label for="logoFileUrl">Logo File Upload:</label>
        <input asp-for="LogoFile" type="file" class="form-control-file" id="logoFileUrl" aria-describedby="fileHelp">
        <h1>@Model.LogoFileUrl</h1>
    </div>
    <div class="form-group">
        <label for="backgroundFileUrl">Background File Upload:</label>
        <input asp-for="BackgroundFile" type="file" class="form-control-file" id="backgroundFileUrl" aria-describedby="fileHelp">
        <h1>@Model.BackgroundFileUrl</h1>
    </div>
    <button type="submit" class="btn btn-primary">Save</button>
</form>

The controller action this HTML form will hit on submit is this web controller action:

public async Task<IActionResult> Save(TenantBranding tenantBranding)
{
    var result =
        await _apiClient.PostAsync("/BrandingSettings", tenantBranding);

    switch (result.Status)
    {
        case HttpStatusCode.NotFound:
        case HttpStatusCode.BadRequest:
            return new RedirectResult("~/Error/404");
        case HttpStatusCode.OK:
            //return View("Edit", result.Message.Content);
        default:
            return new RedirectResult("~/Error/500");
    } 
}

I am further using the FluentClient implementation of Pathoschild.Http.Client.IClient interface to make an API Call to this Post method:

[HttpPost]
public async Task<IActionResult> Post([FromBody] TenantBranding tenantBranding)
{
    if (tenantBranding == null)
    {
        return new BadRequestObjectResult("Invalid Parameter: The incoming tenantBranding parameter is null");
    }

    if (tenantBranding.TenantId == Guid.Empty)
    {
        return new BadRequestObjectResult("Invalid Parameter: The tenantId in the incoming parameter tenantBranding is empty");
    }

    var result = _brandingLogic.Save(tenantBranding).Result;

    if (!result)
    {
        return new JsonResult(500);
    }
    return Ok(); 
}

For some strange reason the tenantbranding parameter is null in the Api Post Method. There is something wrong with the ModelBinding from Web Controller to Api Controller.

This is how my TenantBranding model(Api) looks like:

public class TenantBranding
{
    public Guid TenantId { get; set; }
    public IEnumerable<FormFile> LogoFile { get; set; }
    public IEnumerable<FormFile> BackgroundFile { get; set; }
    public string DocumentType { get; set; }
}

This is how my TenantBranding in Web look like:

public class TenantBranding
{
    public Guid TenantId { get; set; }
    public IFormFile LogoFile { get; set; }
    public IFormFile BackgroundFile { get; set; }
}

But the tenantBranding parameter in the API method is showing null, so I am not sure why this is happening? May it be related to IFormFile ?

At first try to add name attribute to your inputs.

<input asp-for="BackgroundFile" type="file" name="BackgroundFile" class="form-control-file" id="backgroundFileUrl" aria-describedby="fileHelp">

But i suggest you go other way and use ajax request for your api controller:

$(form).on("submit", function(){
    $.ajax({
       url:"api/controller/action",
       type:"POST",
       //here will be your data from FORM
       data:{
                TenantId:$("#tenantid input id").val(),
                LogoFile :$("#LogoFile input id").val(),
                BackgroundFile :$("#BackgroundFile input id").val(),                
            },
      content-type:"application/json",
      success:function(response){// do on success},
      error:function(){// do somesthig on error}
    });
})

When you submit form, js send post request to api controller. This is better way to use WebApi.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM