bircastri
bircastri

Reputation: 2165

How to build base64 rest web service to upload image file with other information

I want to build a Rest Web Service (in .NET) to upload image file with other information like name, description, time etc.

So I have write this code:

[Route("SaveDocument")]
[HttpPost]
public HttpResponseMessage SaveDocument(Stream fileContents)
{

    byte[] buffer = new byte[10000];
    int bytesRead, totalBytesRead = 0;
    do
    {
    bytesRead = fileContents.Read(buffer, 0, buffer.Length);
    totalBytesRead += bytesRead;
    } while (bytesRead > 0);
    Console.WriteLine("Service: Received file {0} with {1} bytes", fileName, totalBytesRead);

}

I want pass file Base64 and I'm not able to do this.

Can we help me?

Upvotes: 3

Views: 2209

Answers (1)

Thomas
Thomas

Reputation: 203

You should wrap your base64 data in an JSON object with your additional information and parse it on your REST backend:

{
    "fileName": "example.jpg",
    "content": "base64-content",
    "creationTime": "2015-10-27T00:10:00"
}

Create some models for your file on the server side and parse your response into objects with the following: https://msdn.microsoft.com/en-us/library/hh674188.aspx

You can then save your file to the disk on your backend with the following command:

File.WriteAllBytes(@"c:\yourfile", Convert.FromBase64String(yourBase64String));

Upvotes: 2

Related Questions