Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. passing a file in to an Core 2.1 WebApi method

passing a file in to an Core 2.1 WebApi method

Scheduled Pinned Locked Moved C#
helpasp-netsysadminjsonquestion
3 Posts 2 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Simon_Whale
    wrote on last edited by
    #1

    I have the following API Controller with a simple method to accept a file via the IFormfile, which works a treat in Postman. Now I need to call this with a HttpClient call from a console application.

    [HttpPost]
    public IActionResult PostFile(IFormFile file)
    {
    //Do Stuff
    Return OK();
    }

    This is where I am stuck can anyone give me a good couple of examples of creating a PostAsync call so that I can transfer a file to the server? Thanks Simon

    Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

    Richard DeemingR 1 Reply Last reply
    0
    • S Simon_Whale

      I have the following API Controller with a simple method to accept a file via the IFormfile, which works a treat in Postman. Now I need to call this with a HttpClient call from a console application.

      [HttpPost]
      public IActionResult PostFile(IFormFile file)
      {
      //Do Stuff
      Return OK();
      }

      This is where I am stuck can anyone give me a good couple of examples of creating a PostAsync call so that I can transfer a file to the server? Thanks Simon

      Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

      Richard DeemingR Offline
      Richard DeemingR Offline
      Richard Deeming
      wrote on last edited by
      #2

      Something like this should work:

      public static async Task UploadFile(HttpClient client, string url, string filePath, string contentType, CancellationToken cancellationToken)
      {
      // Argument validation omitted...

      using (var fileStream = File.OpenRead(filePath))
      {
          var file = new StreamContent(fileStream);
          file.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
          file.Headers.ContentLength = fileStream.Length;
          
          var content = new MultipartFormDataContent();
          content.Add(file, "file", Path.GetFileName(filePath));
          
          using (var response = await client.PostAsync(url, content, cancellationToken).ConfigureAwait(false))
          {
              response.EnsureSuccessStatusCode();
          }
      }
      

      }


      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

      S 1 Reply Last reply
      0
      • Richard DeemingR Richard Deeming

        Something like this should work:

        public static async Task UploadFile(HttpClient client, string url, string filePath, string contentType, CancellationToken cancellationToken)
        {
        // Argument validation omitted...

        using (var fileStream = File.OpenRead(filePath))
        {
            var file = new StreamContent(fileStream);
            file.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
            file.Headers.ContentLength = fileStream.Length;
            
            var content = new MultipartFormDataContent();
            content.Add(file, "file", Path.GetFileName(filePath));
            
            using (var response = await client.PostAsync(url, content, cancellationToken).ConfigureAwait(false))
            {
                response.EnsureSuccessStatusCode();
            }
        }
        

        }


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        S Offline
        S Offline
        Simon_Whale
        wrote on last edited by
        #3

        Richard, Thanks for this and apologies that I have taken so long to respond, had to tweak your solution slightly to make it work

        using (var formData = new MultipartFormDataContent())
        {
        Task responseMessage = null;
        using (var stream = File.OpenRead(pdf))
        {
        HttpContent fileStreamContent = new StreamContent(stream);
        fileStreamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
        { Name = "DigitalPCN", FileName = Path.GetFileName(fine.FileName) };
        fileStreamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
        formData.Add(fileStreamContent);

                        responseMessage = base.PostAsync(new Uri(@"https://localhost:44349/api/Controller/Method"), formData, token);
                        responseMessage.Wait();
                    }
        
                    return responseMessage.Result;
        

        }

        Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

        1 Reply Last reply
        0
        Reply
        • Reply as topic
        Log in to reply
        • Oldest to Newest
        • Newest to Oldest
        • Most Votes


        • Login

        • Don't have an account? Register

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • World
        • Users
        • Groups