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

This is in continuation to my previous post on uploading files. In this post, we would be looking at the second method i.e sending files as part of JSON content.

Again this approach can be used for sending both file and other information in a single request.

Since we are sending the file as part of JSON content (i.e. text format) the prerequisite here is to apply some kind of binary to text encoding. Most common way to do this Base64 encoding (don’t even know the name of others ) .

Below is an example Http request with JSON content having base64 encoded file.

POST https://localhost:44390/api/Upload/JsonUpload HTTP/1.1
Host: localhost:44390
Content-Type: application/json; charset=utf-8
Content-Length: 1338

{"CustomerId":"123123","CustomerName":"ABC Ltd.","ContentType":"application/pdf","FileContent":"wMDAwIG4NCjAwMDAwODc2MzQgMDAwMDAgbg0KMDAwMDA4Nzc2NCAwMDAwMCBuDQowMDAwMDg3ODYxIDAwMDAwIG4NCjAwMDAwOTU2ODIgMDAwMDAgbg0KMDAwMDA5NTc2MCAwMDAwMCBuDQowMDAwMDk5NDkyIDAwMDAwIG4NCnRyYWlsZXIKPDwvU2l6ZSAxNi9JRFs8RTMyMjYzRTU4RDBBRkY4M0E0QUE1QjQzNTZEM0IyMDI+PDJENzU1QzdERDIxREIyMTEwQTAwMDBGNzIwNTBEREZGPl0+PgpzdGFydHhyZWYKMTE2CiUlRU9GCg=="}

Above request has a payload which is JSON and the ‘FileContent’ field has the content of the file being uploaded. On the positive side, this approach is very simple in terms of sending and consuming the request as its pure JSON and its very simple to form and parse a JSON request. On the other hand, it has a performance impact since it uses base64 encoding which increases the size of the file content by approx. 33% (also if CPU cycles are a concern this has an overhead of encoding and decoding as well). So this could be a good approach for small files but not recommended for large files say with a size of more than 5 Mb.

Lets look at the code example

Example

Here is how the API looks like.

[HttpPost]
[Route("JsonUpload")]
public class FileJsonData
{
	public string CustomerId { get; set; }

	public string CustomerName { get; set; }

	public string ContentType { get; set; }

	public string FileContent { get; set; }
}
public IActionResult JsonUpload([FromBody]FileJsonData jsonData)
{
	// Check if the request contains multipart/form-data.
	Byte[] bytes = Convert.FromBase64String(jsonData.FileContent);
	var fileExtension = MimeTypeMap.GetExtension(jsonData.ContentType);
	System.IO.File.WriteAllBytes(GetFilePath("SimpleUpload", "None", fileExtension, fileUploadPath), bytes);
	return Ok();
}

and here is the client code for forming such the request.

 static void PostJson()
{
	using var client = new HttpClient();
	var fileContent = File.ReadAllBytes(uploadFilePath);
	var jsonContent = new { CustomerId = "123123", CustomerName = "ABC Ltd.", ContentType = fileContentType, FileContent = Convert.ToBase64String(fileContent) };
	var requestUri = "/api/Upload/JsonUpload";
	client.BaseAddress = new Uri(apiBaseAddress);
	var result = client.PostAsync(requestUri,new StringContent(JsonConvert.SerializeObject(jsonContent),Encoding.UTF8,"application/json")).Result;
	Console.WriteLine($"Response : {result.StatusCode}");
}

Nothing to explain here as its plain basic JSON content POST.
Next post we will talk about another interesting approach of using Multipart/related content type.

2 thoughts on “Different ways of uploading files using Http based APIs- Part 2

  1. Pingback: Different ways of uploading files using Http based APIs- Part 1 | Coding Canvas

  2. Fakhry

    I’m using this way in uploading files but currently I’m facing a performance issue as my request may contains 6 files with average 5mb.

    Is there any optimizing I can do to avoid timeout.

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.