我见过许多不同的答案'对此,他们都没有完成。这是我目前的上传功能代码。它应该足够完整以供讨论。我在尝试上传.png文件时收到(500)错误。 .png文件被formbytes流使用,但是当它到达最后一行的实际请求时,它会抛出错误。帮助!
public void Upload(string uri, string filePath)
{
FileInfo fi = new FileInfo(filePath);
string fileType = fi.Extension.Replace(".", "");
string slug = fi.Name.Replace(fi.Extension, "");
string formdataTemplate = "Content-Disposition: form-data; name=\"file\" filename=\"{0}\";\r\nContent-Type: application/octet-stream\r\n\r\n";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Accept = "application/json";
if (cookies != null)
{
// cookies is a cookie container populated by another process, works for creating ALM requirements
request.CookieContainer = cookies;
}
request.Headers.Add("slug", slug);
string formitem = "";
byte[] formbytes = null;
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
formitem = string.Format(formdataTemplate, Path.GetFileName(filePath));
formbytes = Encoding.UTF8.GetBytes(formitem);
requestStream.Write(formbytes, 0, formbytes.Length);
byte[] buffer = new byte[1024 * 4];
int bytesLeft = 0;
while ((bytesLeft = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
requestStream.Write(buffer, 0, bytesLeft);
}
}
}
//request.Headers.Add(formbytes);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { }
}
答案 0 :(得分:0)
答案是我必须签出添加附件的要求。这是一个简单的帖子,无需身体,可以:
/休息/域/ [域] /项目/ [项目] /需求/ [ENTITYID] /版本/检出
你可以办理登机手续,也不需要身体:
/休息/域/ [域] /项目/ [项目] /需求/ [ENTITYID] /版本/检出