Skip to content

Instantly share code, notes, and snippets.

@kamend
Last active January 20, 2025 15:13
Show Gist options
  • Save kamend/7cd39690ba0f90c4da29ecf60fcc05a3 to your computer and use it in GitHub Desktop.
Save kamend/7cd39690ba0f90c4da29ecf60fcc05a3 to your computer and use it in GitHub Desktop.
Upload image to Replicate through Unity and C#
[Serializable]
public class ReplicateImageUploadResponse
{
public string id;
public ReplicateImageUploadUrlsResponse urls;
}
[Serializable]
public class ReplicateImageUploadUrlsResponse
{
public string get;
}
async UniTask<string> UploadImageToReplicate(string imagePath, CancellationToken ct)
{
string apiUri = "https://api.replicate.com/v1/files";
byte[] fileBytes = await File.ReadAllBytesAsync(imagePath);
string filename = Path.GetFileName(imagePath);
List<IMultipartFormSection> requestData = new List<IMultipartFormSection>();
requestData.Add(new MultipartFormFileSection("content", fileBytes,filename,"application/octet-stream"));
using var www = UnityWebRequest.Post(apiUri, requestData);
www.SetRequestHeader("Authorization", $"Bearer {REPLICATE_API_TOKEN}");
await www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
throw new Exception("Could not upload image to replicate..");
var json = www.downloadHandler.text;
ReplicateImageUploadResponse response = JsonUtility.FromJson<ReplicateImageUploadResponse>(json);
Debug.Log("Replicate url: "+response.urls.get);
return response.urls.get;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment