Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link

asp.net core web API file upload and “form-data” multiple parameter passing to method

1 min read

 Cách 1:

 


It works 100%. Tested. Please do the below steps:


You should create a custom class for the model as


public class FileInputModel

{

    public string Name { get; set; }

    public IFormFile FileToUpload { get; set; }

<code>

<form asp-action="UploadFileViaModel" asp-controller="Home" enctype="multipart/form-data" method="post">

    <input class="form-control" name="Name" />

    <input class="form-control" name="FileToUpload" type="file" />

    <input class="btn btn-default" type="submit" value="Create" />

</form> 

</code>

<code>

[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");

}

  <code>

  

Cách 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; }

}

    

    

    

Cách 3:

 


I tested with the following code and it works:


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; }

    }

}

Note that you need to use a model.


Here is the postman screen shot below with the same attributes.


Postman screenshot below


UPDATE for multiple files:


Change the model to:


public class Model

{

    public List<iformfile> Files { get; set; }

    public string Param { get; set; }

}

Postman screenshot: Multipart form content


Update 2


The content type header is multipart/form-data


Here is a screenshot of it working:


Working Code</iformfile></code></iactionresult></code>



Nguồn:

https://stackoverflow.com/questions/51892706/asp-net-core-web-api-file-upload-and-form-data-multiple-parameter-passing-to-m

Đăng nhận xét