以下是片段:
Function Encode(ByVal dec As String) As String
Dim bt() As Byte
ReDim bt(dec.Length)
bt = System.Text.Encoding.ASCII.GetBytes(dec)
Dim enc As String
enc = System.Convert.ToBase64String(bt)
Return enc
End Function
我正在尝试制作一个程序,用于发送图像以便上传到网站。这是Python中的代码,我试图将它移植到C#,但它有点令人困惑,因为我不知道任何python。
#!/usr/bin/python
import pycurl
c = pycurl.Curl()
values = [
("key", "YOUR_API_KEY"),
("image", (c.FORM_FILE, "file.png"))]
# OR: ("image", "http://example.com/example.jpg"))]
# OR: ("image", "BASE64_ENCODED_STRING"))]
c.setopt(c.URL, "http://imgur.com/api/upload.xml")
c.setopt(c.HTTPPOST, values)
c.perform()
c.close()
我是否应该将image.png文件转换为Base64字符串?请帮忙。
答案 0 :(得分:4)
VB.NET到C#:
string Encode(string dec)
{
return
Convert.ToBase64String(
Encoding.ASCII.GetBytes(dec));
}
所以你在谈论Python到C#(文件上传):
WebClient wc = new WebClient();
wc.UploadFile("http://imgur.com/api/upload.xml", "POST", "file.png");
如果您确实需要设置这些字段名称,可能这个脚本是一个更好的开始,因为它从头开始构建请求:Upload files with HTTPWebrequest (multipart/form-data)
另外,试试这个:
WebClient wc = new WebClient();
wc.UploadData(
"http://imgur.com/api/upload.xml", "POST",
Encoding.UTF8.GetBytes(
String.Join("&",
new Dictionary<string, string>()
{
{ "key", "YOUR_API_KEY" },
{ "image", Convert.ToBase64String(File.ReadAllBytes("file.png"))}
}.Select(item =>
String.Format("{0}={1}",
item.Key, HttpUtility.UrlEncode(item.Value)))
.ToArray())));