Receive file and other form data together in ASP.NET Core Web API (boundary based request parsing)

前端 未结 7 684
悲&欢浪女
悲&欢浪女 2020-12-30 00:32

How would you form your parameters for the action method which is supposed to receive one file and one text value from the request?

I tried

相关标签:
7条回答
  • 2020-12-30 01:21

    In HomeController.cs

    using Microsoft.AspNetCore.Hosting;
    .......
    private IHostingEnvironment _environment;
    
    public HomeController(IHostingEnvironment environment)
    {
        _environment = environment;
    }
    
    [HttpPost]
    [ValidateAntiForgeryToken]        
    public IActionResult Index(IFormCollection formdata)
    {
     var files = HttpContext.Request.Form.Files;
     foreach (var file in files)
     {
         var uploads = Path.Combine(_environment.WebRootPath, "Images");
         if (file.Length > 0)
         {
            string FileName = Guid.NewGuid(); // Give file name
            using (var fileStream = new FileStream(Path.Combine(uploads, FileName), FileMode.Create))
            {
                file.CopyToAsync(fileStream);
            }       
         }
      }
    }
    

    In view - Index.cshtml

    <form method="post" enctype="multipart/form-data" >
     .....
    </form>
    

    You can try this code.

    Thanks!!

    0 讨论(0)
提交回复
热议问题