我似乎无法使用此代码Streamsends API
。我一直在互联网上,发现与我正在尝试做的事情有关的信息很少。我正在尝试将文件上传到他们的服务器。任何人都可以看看这个,也许可以帮助我吗?
我不断从 Streamsends 服务器收到 500 错误,他们说这是在 Streamsend 应用程序本身中。有趣的是,如果我在注释掉的底部附近取线
( //request.ContentType = "multipart/form-data";
)
并取消注释我收到一个 422 错误,表示数据无效。边界好像有问题。
我对 C# 相当陌生,这是我第一次使用 Streamsends API,因此将不胜感激。
m_Method = "POST"
m_Action = "uploads"
private string StreamSendResponse(string Path, string FileName)
{
string sReturn = String.Empty;
string sLocation = String.Empty;
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes(Environment.NewLine + "--" + boundary + Environment.NewLine);
Uri addy = new Uri(m_URI + m_Action);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(addy);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = m_Method;
request.KeepAlive = true;
request.Headers.Add("Authorization", "Basic " + Merv.base64Encode(m_ID + ":" + m_Key));
Stream rs = request.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n{1}";
NameValueCollection nvc = new NameValueCollection();
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n";
string header = string.Format(headerTemplate, "data", FileName);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(Path + FileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes(Environment.NewLine + "--" + boundary + "--" + Environment.NewLine);
rs.Write(trailer, 0, trailer.Length);
rs.Close();
request.Accept = "application/xml";
//request.ContentType = "multipart/form-data";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader srResponse = new StreamReader(response.GetResponseStream());
sLocation = response.Headers["Location"];
sReturn = srResponse.ReadToEnd().Trim();
}
catch (WebException exc)
{
StreamReader srResponse = new StreamReader(response.GetResponseStream());
sReturn = srResponse.ReadToEnd().Trim();
sLocation = exc.Message;
}
if (sReturn == String.Empty)
{
sReturn = sLocation;
}
return sReturn;
}