public static async Task<string> UploadImageAsync(Image bitmap) { var memoryStream = new MemoryStream(); bitmap.Save(memoryStream, ImageFormat.Png); memoryStream.Seek(0, SeekOrigin.Begin); var streamContent = new StreamContent(memoryStream); streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png"); var multipartDataContent = new MultipartFormDataContent { {streamContent, "shot", "screenshot.png"} }; var responseMessage = await _httpClient.PostAsync(API_URL, multipartDataContent); if (!responseMessage.IsSuccessStatusCode) return null; var responseString = await responseMessage.Content.ReadAsStringAsync(); var json = _javaScriptSerializer.Deserialize<dynamic>(responseString); streamContent.Dispose(); multipartDataContent.Dispose(); if (json["result"] == ":(") { Console.WriteLine("Error!"); Console.WriteLine(json["error"]["code"]); Console.WriteLine(json["error"]["message"]); } return json["link"]; }
public static async Task<String> CreatePageWithImage(string token, string apiRoute, string content, StorageFile file) { // This is the file that was saved by the user as a gif (see previous blog post) Stream fileStream = await file.OpenStreamForReadAsync(); var client = new HttpClient(); // Note: API only supports JSON return type. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // I'm passsing in the token here because I get it when the user logs in but you can easily get it using the LiveIdAuth class: // await LiveIdAuth.GetAuthToken() client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); string imageName = file.DisplayName; string date = DateTime.Now.ToString(); string simpleHtml = "<html>" + "<head>" + "<title>" + date + ": " + imageName + "</title>" + "<meta name=\"created\" content=\"" + date + "\" />" + "</head>" + "<body>" + "<p>" + content + "<p>" + "<img src=\"name:" + imageName + "\" alt=\"" + imageName + "\" width=\"700\" height=\"700\" />" + "</body>" + "</html>"; HttpResponseMessage response; // Create the image part - make sure it is disposed after we've sent the message in order to close the stream. using (var imageContent = new StreamContent(fileStream)) { imageContent.Headers.ContentType = new MediaTypeHeaderValue("image/gif"); // Post request to create a page in the Section "Jots" https://www.onenote.com/api/v1.0/pages?sectionName=Jots var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "pages?sectionName=" + WebUtility.UrlEncode("Jots")) { Content = new MultipartFormDataContent { {new StringContent(simpleHtml, Encoding.UTF8, "text/html"), "Presentation"}, {imageContent, imageName} } }; // Must send the request within the using block, or the image stream will have been disposed. response = await client.SendAsync(createMessage); imageContent.Dispose(); } return response.StatusCode.ToString(); }
public void UploadExtensionLibraryAsync(string selectedFileName, byte[] fileContents, ObservableCollection<string> assemblies, object userState) { Uri uri = CreateRestRequest("Extensions/Upload"); var assembliesString = assemblies != null ? string.Join(",", assemblies) : null; var content = new MultipartFormDataContent(); var ms = new MemoryStream(fileContents); var fileContent = new StreamContent(ms); // Specify the content disposition and content type - without this the form data will not // be included in the Request object in .NET 2.0 app pools fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"files\"", FileName = "\"" + selectedFileName + "\"" }; fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-silverlight-app"); content.Add(fileContent); var stringContent = new StringContent(assembliesString); // Need to specify the content disposition and content type for .NET 2.0 compatibility here, too stringContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"assemblies\"" }; stringContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); content.Add(stringContent); var client = new HttpClient(); client.PostAsync(uri, content).ContinueWith(t => { stringContent.Dispose(); fileContent.Dispose(); ms.Dispose(); content.Dispose(); if (t.IsCanceled) return; if (t.Exception != null) { var errorDisplay = new ErrorDisplay(); // Attempt to get the stack trace with IL offsets string stackTraceIL = t.Exception.StackTraceIL(); ErrorData data = new ErrorData() { Message = t.Exception.Message, StackTrace = !string.IsNullOrEmpty(stackTraceIL) ? stackTraceIL : t.Exception.StackTrace }; errorDisplay.DataContext = data; // Size the error UI double width = Application.Current.RootVisual.RenderSize.Width * 0.67; errorDisplay.Width = width > errorDisplay.MaxWidth ? errorDisplay.MaxWidth : width; errorDisplay.Completed += (o, a) => BuilderApplication.Instance.HideWindow(errorDisplay); // Show the error BuilderApplication.Instance.ShowWindow(Strings.ErrorOccured, errorDisplay, false, null, null); } if (UploadExtensionLibraryCompleted != null) { UploadExtensionLibraryCompleted(this, new UploadExtensionLibraryCompletedEventArgs() { Error = t.Exception, UserState = userState, }); } }, TaskScheduler.FromCurrentSynchronizationContext()); }