CSharp - 使用 web request提交附件

  显示原文与译文双语对照的内容
143 0

我正在尝试向 REST API 提交附件。 附件未正确提交。 我相信我的请求出了点问题


RunQueryimage("http://www.extremetech.com/wp-content/uploads/2012/12/Audi-A1.jpg);

public string RunQueryimage(string imagePath)
 {

//do get request
 HttpWebRequest request = (HttpWebRequest)
 WebRequest.Create("https://iss.ontimenow.com/api/v2/incidents/");
 request.ContentType ="application/octet-stream";
 request.Method ="POST";

 var webClient = new WebClient();
 byte[] bytearr = webClient.DownloadData(imagePath);
 var filecontent = new ByteArrayContent(bytearr);
//request.ContentLength = 0;

 if (filecontent!= null)
 {
 using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
 {
 writer.Write(filecontent);

 }
 }


 HttpWebResponse response = (HttpWebResponse)
 request.GetResponse();


 string result = string.Empty;
 using (StreamReader reader = new StreamReader(response.GetResponseStream()))
 {
 result = reader.ReadToEnd();
 }

 return result;


 }

时间: 原作者:

97 2

你在创建web请求时已经打开了一个流。

更改这里选项:


byte[] bytearr = webClient.DownloadData(imagePath); 
var filecontent = new ByteArrayContent(bytearr);
//request.ContentLength = 0;

 if (filecontent!= null)
 {
 using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
 {
 writer.Write(filecontent);

 }
 }

到:


 byte[] fileContent = webClient.DownloadData(imagePath);

 if (fileContent!= null)
 {
 Stream requestStream = request.GetRequestStream();
 requestStream.Write(fileContent, 0, fileContent.Length);
 requestStream.Close();
 }

...