skip to Main Content

I’m trying to upload a file using swagger/postman using .net framework

The issue that I’m facing is that in .NET Core you can simply just use IFormFile within your Model class and you’re basically all set

But now that I’m not using .NET Core, I’m lost

The goal is to make a POST request that contains a String and File

public class UploadDoc
{
     public string Desc { get; set; }
     public HttpRequest File { get; set; }//I've tried different things here 
}

And here is the post

    public async Task<IHttpActionResult> Post(UploadDoc uploadDoc)
    {
        if (!Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        var provider = new MultipartMemoryStreamProvider();
        await Request.Content.ReadAsMultipartAsync(provider);
        foreach (var file in provider.Contents)
        {
            var buffer = await file.ReadAsByteArrayAsync();
            
            File.WriteAllBytes(@"abcdef.pdf", buffer);
        }

        return Ok();
    }

Edit: Adding more clarification — my goal is to create an API Post call and ultimately, all I want is to take 2 inputs from the user

  • Input 1: A string
  • Input 2: A PDF File

So the postman request should look like this

enter image description here

When using .NET Core 6, I could do this simply by creating a model class that had

public string Desc { get; set; }
public IFormFile? formFile { get; set; }

And then setting up my API Call like so:

    [HttpPost]
    public async Task<IActionResult> Post([FromForm] DummyModel dummyModel)
    {
        var uploadedDocument = await FileHelper.UploadImage(dummyModel.formFile); // this dummyModel.formFile would contain what was uploaded by the user
    }

Now I’m trying to figure out how to do something similar within .NET Framework Web API

Edit 2:

I think I need to use the multipartformdata thing but my issue is I want my end-user to always only send me 2 things

A string and a PDF File

2

Answers


  1. Not sure I fully understand your question, but to post in .NET you could:

    // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
    static readonly HttpClient client = new HttpClient();
    
    static async Task Main()
    {
        // Call asynchronous network methods in a try/catch block to handle exceptions.
        try 
        {
            var myPayload = new **whatever** // HttpContent, including System.Net.Http.MultipartContent
            HttpResponseMessage response = await client.PostAsync("http://www.contoso.com/", myPayload);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
    
            Console.WriteLine(responseBody);
        }
        catch(HttpRequestException e)
        {
            Console.WriteLine("nException Caught!");   
            Console.WriteLine("Message :{0} ",e.Message);
        }
    }
    

    see:
    https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.postasync?view=net-6.0#system-net-http-httpclient-postasync(system-uri-system-net-http-httpcontent)

    and:
    https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent?view=net-6.0

    Login or Signup to reply.
  2. public class UploadDoc
    {
        public string Desc { get; set; }
        public System.Web.HttpPostedFileBase FileToUpload { get; set; } 
    }
    
    public async Task<IHttpActionResult> Post(UploadDoc fileToUpload)
    {
        // Does not do anything with fileToUpload.Desc
        if (fileToUpload.ContentLength > 0)
            {
                savedFile = System.IO.Path.Combine(
                "LocationToSaveTo"
                , "FileName" + System.IO.Path.GetExtension(fileToUpload.FileName));
    
                fileToUpload.SaveAs(savedFile);
            }
    
        return Ok();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search