[英]Send file to service using Microsoft.Net.Http
I have a method: 我有一个方法:
private bool UploadFile(Stream fileStream, string fileName)
{
HttpContent fileStreamContent = new StreamContent(fileStream);
using (var client = new HttpClient())
{
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent, fileName, fileName);
var response = client.PostAsync("url", formData).Result;
return response.StatusCode == HttpStatusCode.OK;
}
}
}
}
That is sending the file to a WCF service, but looking at the Wireshark log of the post, the fileStream isn't being appended, just the filename. 那就是将文件发送到WCF服务,但是查看该帖子的Wireshark日志,并没有附加文件流,只是附加了文件名。 Do I need to do something else?
我还需要做其他事情吗?
Use a ByteArrayContent
instead of a stream content. 使用
ByteArrayContent
代替流内容。
var fileContent = new ByteArrayContent(File.ReadAllBytes(fileName));
Then specify your content disposition header: 然后指定您的内容处置标题:
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
formData.Add(fileContent);
Turns out the fileStream wasn't getting to the method. 原来fileStream没有进入该方法。 Using
context.Request.Files[0].InputStream
seemed to be the culprite. 使用
context.Request.Files[0].InputStream
似乎是罪魁祸首。 Using .SaveAs and then reading it in as a byteArray and attaching that to the MultiPartFormDataContent worked. 使用.SaveAs,然后将其读取为byteArray并将其附加到MultiPartFormDataContent即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.