3

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?

bircastri
  • 2,169
  • 13
  • 50
  • 119
  • Possible duplicate of [How To Accept a File POST - ASP.Net MVC 4 WebAPI](http://stackoverflow.com/questions/10320232/how-to-accept-a-file-post-asp-net-mvc-4-webapi) – pask23 Oct 27 '15 at 15:16

1 Answers1

2

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));
Thomas
  • 213
  • 2
  • 9