How to set up a Web API controller for multipart/form-data

前端 未结 8 2114
萌比男神i
萌比男神i 2020-11-27 02:51

I am trying to figure this out. I was not getting any useful error messages with my code so I used something else to generate something. I have attached that code after the

相关标签:
8条回答
  • 2020-11-27 03:35

    Here's another answer for the ASP.Net Core solution to this problem...

    On the Angular side, I took this code example...

    https://stackblitz.com/edit/angular-drag-n-drop-directive

    ... and modified it to call an HTTP Post endpoint:

      prepareFilesList(files: Array<any>) {
    
        const formData = new FormData();
        for (var i = 0; i < files.length; i++) { 
          formData.append("file[]", files[i]);
        }
    
        let URL = "https://localhost:44353/api/Users";
        this.http.post(URL, formData).subscribe(
          data => { console.log(data); },
          error => { console.log(error); }
        );
    

    With this in place, here's the code I needed in the ASP.Net Core WebAPI controller:

    [HttpPost]
    public ActionResult Post()
    {
      try
      {
        var files = Request.Form.Files;
    
        foreach (IFormFile file in files)
        {
            if (file.Length == 0)
                continue;
            
            string tempFilename = Path.Combine(Path.GetTempPath(), file.FileName);
            System.Diagnostics.Trace.WriteLine($"Saved file to: {tempFilename}");
    
            using (var fileStream = new FileStream(tempFilename, FileMode.Create))
            {
                file.CopyTo(fileStream);
            }
        }
        return new OkObjectResult("Yes");
      }
      catch (Exception ex)
      {
        return new BadRequestObjectResult(ex.Message);
      }
    }
    

    Shockingly simple, but I had to piece together examples from several (almost-correct) sources to get this to work properly.

    0 讨论(0)
  • 2020-11-27 03:38

    I normally use the HttpPostedFileBase parameter only in Mvc Controllers. When dealing with ApiControllers try checking the HttpContext.Current.Request.Files property for incoming files instead:

    [HttpPost]
    public string UploadFile()
    {
        var file = HttpContext.Current.Request.Files.Count > 0 ?
            HttpContext.Current.Request.Files[0] : null;
    
        if (file != null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
    
            var path = Path.Combine(
                HttpContext.Current.Server.MapPath("~/uploads"),
                fileName
            );
    
            file.SaveAs(path);
        }
    
        return file != null ? "/uploads/" + file.FileName : null;
    }
    
    0 讨论(0)
  • 2020-11-27 03:38

    You're getting HTTP 415 "The request entity's media type 'multipart/form-data' is not supported for this resource." because you haven't mention the correct content type in your request.

    0 讨论(0)
  • 2020-11-27 03:41

    Perhaps it is late for the party. But there is an alternative solution for this is to use ApiMultipartFormFormatter plugin.

    This plugin helps you to receive the multipart/formdata content as ASP.NET Core does.

    In the github page, demo is already provided.

    0 讨论(0)
  • 2020-11-27 03:42

    5 years later on and .NET Core 3.1 allows you to do specify the media type like this:

    [HttpPost]
    [Consumes("multipart/form-data")]
    public IActionResult UploadLogo()
    {
        return Ok();
    }
    
    0 讨论(0)
  • 2020-11-27 03:48

    This is what solved my problem
    Add the following line to WebApiConfig.cs

    config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));
    
    0 讨论(0)
提交回复
热议问题