Different ways of uploading files using Http based APIs- Part 4

In this last post on uploading files, I’ll show you the most simple way of uploading files using HTTP. This is most suitable if you just want to upload a file without any metadata.
In this case, we just send content (binary or text ) of the file in the POST body with the content-type header set to the mime type of the file as shown below.

POST https://localhost:44390/api/Upload/SimpleUpload HTTP/1.1
Host: localhost:44390
Content-Type: application/pdf
Content-Length: 20702285

[PDF Content]

In case you want to upload a file with metadata then you would need two requests in this case with first one defining metadata and sending it to the server (which would include a unique request identifier) and second one having only the file content with the unique request identifier. This unique request identifier will then be used on the server to attach metadata to the file.
Let’s look at a code example

Example

Here is the API code

 [HttpPost]
 [Route("SimpleUpload")]
 public IActionResult SimpleUpload()
 {
      var fileExtension = MimeTypeMap.GetExtension(Request.ContentType);

       using var stream = System.IO.File.Create(GetFilePath("SimpleUpload", "None", fileExtension, fileUploadPath));
      Request.BodyReader.AsStream().CopyToAsync(stream).Wait();
       return Ok();
 }

and below is the client code for posting API request.

 static void PostSimple()
 {
           using var client = new HttpClient();
            using var content = new ByteArrayContent(File.ReadAllBytes(uploadFilePath));
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(fileContentType);
            var requestUri = "/api/Upload/SimpleUpload";
            client.BaseAddress = new Uri(apiBaseAddress);
            
            var result = client.PostAsync(requestUri, content).Result;
            Console.WriteLine($"Response : {result.StatusCode}");
 }

It’s pretty simple and self-explanatory. For posting, we just read the byte array content and put it in the post body with the content type as mime type of the file. And while reading we read the POST body as stream to get the content.

Tagged on: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.