作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在尝试开发使用 Imgur api 上传图像的 C# 应用程序。
这是我的上传功能:
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(System.Convert.ToBase64String(imageData)) + "&key=" + apiKey;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/image");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Headers["Authorization"] = "Client-ID abd937cc5e11dc9";
StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
streamWriter.Write(uploadRequestString);
streamWriter.Close();
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
return responseReader.ReadToEnd();
}
如果我上传小图片 (20kb) 一切正常。但是当我上传更大的图像(500kb)时,我得到了错误:无效的 URI:Uri 字符串太长。
我能做什么?
最佳答案
我通过分割base64字符串成功上传大图
这是工作代码:
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();
const int MAX_URI_LENGTH = 32766;
string base64img = System.Convert.ToBase64String(imageData);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < base64img.Length; i += MAX_URI_LENGTH)
{
sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(MAX_URI_LENGTH, base64img.Length - i))));
}
string uploadRequestString = "key=" + apiKey + "&title=" + "imageTitle" +
"&caption=" + "img" + "&image=" + sb.ToString();
// string uploadRequestString = "image=" + Uri.EscapeDataString(System.Convert.ToBase64String(imageData)) + "&key=" + apiKey;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/image");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Headers["Authorization"] = "Client-ID abd937cc5e11dc9";
StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
streamWriter.Write(uploadRequestString);
streamWriter.Close();
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
return responseReader.ReadToEnd();
}
感谢大家。
关于c# - 将图像上传到 imgur 导致 : The Uri string is too long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16267649/
我是一名优秀的程序员,十分优秀!