我有一个函数,我通过它调用我的REST API。我需要在请求中传递图像。我如何实现这一目标?
代表:
public int Save(Image image)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
}
在这里,我如何传递我的图像'根据我的要求' req'?
答案 0 :(得分:1)
尝试使用以下内容:
req.ContentType = "multipart/form-data";
using (var ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); //if it is jpeg
string encoded = Convert.ToBase64String(ms.ToArray());
byte[] reqData = Encoding.UTF8.GetBytes(encoded);
using (var stream = req.GetRequestStream())
{
stream.Write(reqData, 0, reqData.Length);
}
}
答案 1 :(得分:0)
你可以在客户端做这样的事情:
HttpClient client = new HttpClient();
var imageStream = File.OpenRead(@"C:\p1.jpg");
var content = new StreamContent(imageStream);
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
var response = await client.PostAsync("URL", content);
您可以从NugetPackage中获取 HttpClient Microsoft.Net.Http
在REST API端(接收端),您可以从Request.Content对象中获取它,如下所示:
public void Post()
{
using (var fileStream = File.Create("C:\\NewFile.jpg"))
{
using (MemoryStream tempStream = new MemoryStream())
{
var task = this.Request.Content.CopyToAsync(tempStream);
task.Wait();
tempStream.Seek(0, SeekOrigin.Begin);
tempStream.CopyTo(fileStream);
tempStream.Close();
}
}
}