Search code examples
c#.netexceptionuriimgur

Invalid URI: The Uri string is too long using Imgur API


I am using imgur API to upload images but i am getting an exception on this line:

string uploadRequestString = "image=" + Uri.EscapeDataString(Convert.ToBase64String(imageData)) + "&key=" + apiKey;

Invalid URI: The Uri string is too long.

Full code:

public static string PostToImgur(string imagFilePath, string apiKey)
{
    byte[] imageData;
    FileStream fileStream = File.OpenRead(imagFilePath);
    imageData = new byte[fileStream.Length];
    fileStream.Read(imageData, 0, imageData.Length);
    fileStream.Close();

    string uploadRequestString = "image=" + Uri.EscapeDataString(Convert.ToBase64String(imageData)) + "&key=" + apiKey;

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://api.imgur.com/2/upload");
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ServicePoint.Expect100Continue = false;

    StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
    streamWriter.Write(uploadRequestString);
    streamWriter.Close();

    WebResponse response = webRequest.GetResponse();
    Stream responseStream = response.GetResponseStream();
    StreamReader responseReader = new StreamReader(responseStream);

    string responseString = responseReader.ReadToEnd();

    XmlDocument doc = new XmlDocument();
    doc.InnerXml = responseString;
    XmlElement root = doc.DocumentElement;
    responseString = root.GetElementsByTagName("original")[0].InnerText;

    return responseString;
}

It works for smaller size file but getting that error on large files.


Solution

  • I suspect that the output from System.Convert.ToBase64String(imageData) is too long to be a valid URI which is around 2000 characters (I think it's 2048).

    This will be related to the size of the image as a smaller image can be encoded into a shorter string.

    You aren't going to be able to get round this limit.