Skip to content

Instantly share code, notes, and snippets.

@philippgille
Created February 29, 2016 16:20
Show Gist options
  • Save philippgille/c0bc42433888fa79864a to your computer and use it in GitHub Desktop.
Save philippgille/c0bc42433888fa79864a to your computer and use it in GitHub Desktop.
Sample code for uploading a file to apiOmat
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace FileUploadSample
{
/* Sample file upload for apiOmat v2.0.x with C# / .NET 4.5 */
class Program
{
static readonly string scheme = "https";
static readonly string baseUrl = "apiomat.org";
static readonly int port = 443;
static readonly string appName = null; // TODO: replace by actual app name
static readonly string apiKey = null; // TODO: replace by actual API key
static readonly string fileName = "exampleFile";
static readonly string fileFormat = "dat";
static void Main(string[] args)
{
byte[] data = GetData();
string location = UploadFile(data, scheme, baseUrl, port, appName, apiKey, fileName, fileFormat);
if (location == null)
{
Console.WriteLine("Upload failed");
}
else
{
Console.WriteLine("Uploaded successfully");
Console.WriteLine("File location: " + location);
}
Console.ReadLine();
}
/* Replace implementation by loading a file via stream or something similar */
private static byte[] GetData()
{
Random rnd = new Random();
Byte[] b = new Byte[10];
rnd.NextBytes(b);
return b;
}
/* Uploads a file to apiOmat */
private static string UploadFile(byte[] data, string scheme, string baseUrl, int port, string appName, string apiKey, string fileName, string fileFormat)
{
string location = null;
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Clear();
string fileUploadRestResource = scheme + "://" + baseUrl + ":" + port.ToString() + "/yambas/rest/apps/" + appName + "/data/files";
string urlParams = "?name=" + fileName + "&format=" + fileFormat;
string fullUrlAsString = fileUploadRestResource + urlParams;
HttpRequestMessage reqMessage = new HttpRequestMessage();
reqMessage.RequestUri = new Uri(fullUrlAsString);
reqMessage.Method = HttpMethod.Post;
reqMessage.Headers.Add("x-apiomat-apikey", apiKey);
reqMessage.Content = new ByteArrayContent(data);
HttpResponseMessage response = client.SendAsync(reqMessage).Result;
if (response.IsSuccessStatusCode)
{
location = response.Headers.Location.ToString();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return location;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment