Skip to content

Instantly share code, notes, and snippets.

@faejr
Last active April 6, 2016 16:04
Show Gist options
  • Save faejr/c1745d02389c85c4fac17821c404275b to your computer and use it in GitHub Desktop.
Save faejr/c1745d02389c85c4fac17821c404275b to your computer and use it in GitHub Desktop.
Basic function to handle file uploads using xamarin.mac
//Upload function using the native functionality of Mac
public static string UploadNative (string url, byte [] paramFileBytes, string fileFormName, Dictionary<string, string> args)
{
NSData actualFile = NSData.FromArray (paramFileBytes);
NSString urlString = (NSString)url;
//we're gonna send byte data
NSMutableUrlRequest request = new NSMutableUrlRequest ();
request.Url = new NSUrl(urlString);
request.HttpMethod = "POST";
string boundary = "---------------------------14737809831466499882746641449";
NSString contentType = new NSString (string.Format("multipart/form-data; boundary={0}", boundary));
var keys = new object [] { "Content-Type" };
var objects = new object [] { contentType };
var dictionary = NSDictionary.FromObjectsAndKeys (objects, keys);
request.Headers = dictionary;
NSMutableData body = new NSMutableData ();
body.AppendData (NSData.FromString(new NSString(string.Format("\r\n--{0}\r\n", boundary))));
body.AppendData (NSData.FromString(new NSString(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{0}.png\"\r\n", fileFormName))));
body.AppendData (NSData.FromString (new NSString ("Content-Type: application/octet-stream\r\n\r\n")));
body.AppendData (actualFile);
body.AppendData (NSData.FromString(new NSString(string.Format("\r\n--{0}--\r\n", boundary))));
foreach (KeyValuePair<string, string> kvp in args) {
body.AppendData (NSData.FromString (new NSString (string.Format ("\r\n--{0}\r\n", boundary))));
body.AppendData (NSData.FromString (new NSString (string.Format ("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", kvp.Key))));
body.AppendData (NSData.FromString (new NSString(kvp.Value)));
body.AppendData (NSData.FromString (new NSString (string.Format ("\r\n--{0}--\r\n", boundary))));
}
request.Body = body;
NSUrlResponse resp;
NSError err;
NSData returnData = NSUrlConnection.SendSynchronousRequest (request, out resp, out err);
return NSString.FromData (returnData, NSStringEncoding.UTF8).ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment