Skip to content

Instantly share code, notes, and snippets.

@tdeck
Last active April 20, 2019 15:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdeck/a0d61ff19ca8fc2cf64d to your computer and use it in GitHub Desktop.
Save tdeck/a0d61ff19ca8fc2cf64d to your computer and use it in GitHub Desktop.
Example showing how to upload item images to the Square Connect API in C#
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.IO;
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
static class ImageUploader
{
const string DOMAIN = "https://connect.squareup.com";
const string ITEM_ID = "<your-item-id>";
const string BEARER_TOKEN = "<your-personal-access-token>";
const string IMAGE_FILE = "cat.jpg";
[DataContract]
private struct ItemImage
{
[DataMember]
public string id;
[DataMember]
public string url;
}
// Uploads the image for a given item.
// Returns a URL.
static async public Task<string> UploadImage(
string accessToken, string itemID, string imageFile)
{
using (var client = new HttpClient())
{
// Configure the "Authorization: Bearer ..." HTTP header
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
// Read the image data and add it as an HTTP multipart form data item
var imageContent = new ByteArrayContent(File.ReadAllBytes(imageFile));
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
var requestContent = new MultipartFormDataContent();
requestContent.Add(imageContent, "image_data", Path.GetFileName(imageFile));
// POST the image to the server
var url = DOMAIN + "/v1/me/items/" + itemID + "/image";
var response = await client.PostAsync(url, requestContent);
response.EnsureSuccessStatusCode();
// (Optional) Parse the URL out of the response using DataContractSerializer.
// There are nicer ways to parse JSON in C#, but this way uses only built-in
// libraries.
var jsonStream = await response.Content.ReadAsStreamAsync();
var itemImage = (ItemImage)
(new DataContractJsonSerializer(typeof(ItemImage)))
.ReadObject(jsonStream);
return itemImage.url;
}
}
static void Main()
{
// Here I'm just wrapping this async code in a Task so I can run it
// inside Main()
Task.Run(async() =>
{
var url = await UploadImage(
BEARER_TOKEN,
ITEM_ID,
IMAGE_FILE
);
Console.WriteLine("Uploaded image URL: " + url);
}
).Wait();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment