Search code examples
c#onenote

OneNote API Create Image showing red x


Trying to capture an image to OneNote API using the Windows Store example is proving a bit difficult.

I am getting a "red x" rather than the image. It looks like the image source is not correct, but I've made a number of changes.

Below is my code: (Any help would be appreciated)

private async void btnCreatePage_Click(object sender, RoutedEventArgs e)
        {
            await CreatePageWithImage();
        }


 private async Task CreatePageWithImage()
        {
            var client = new HttpClient();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            if (IsAuthenticated)
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authClient.Session.AccessToken);
            }

            const string imagePartName = "assets\\Asthma.jpg";
            string date = GetDate();
            string simpleHtml = "<html>" +
                                "<head>" +
                                "<title>A simple page created with an image on it</title>" +
                                "<meta name=\"created\" content=\"" + date + "\" />" +
                                "</head>" +
                                "<body>" +
                                "<h1>This is a page with an ximage on it</h1>" +
                                "<img src=\"name:" + imagePartName + "\" alt=\"A beautiful logo\" width=\"426\" height=\"68\" />" +
                                "</body>" +
                                "</html>";

       // Create the image part - make sure it is disposed after we've sent the message in order to close the stream.
            HttpResponseMessage response;

    using (var imageContent = new StreamContent(await GetBinaryStream("assets\\Asthma.jpg")))
            {
                imageContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                HttpRequestMessage createMessage = new HttpRequestMessage(HttpMethod.Post, PagesEndPoint)
                {
                    Content = new MultipartFormDataContent
                    {
                        {new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html"), "Presentation"},
                        {imageContent, imagePartName}
                    }
                };
                // Must send the request within the using block, or the image stream will have been disposed.
                response = await client.SendAsync(createMessage);
            }
            tbResponse.Text = response.ToString();
        }

Solution

  • In your code, you have set the media type to "image/jpg". This should be set to "image/jpeg" instead. You will also need to change the imagePartName to remove the "\".

    -- James (@jmslau)