我需要从 WinRT 应用创建 POST
请求,其中应包含 StorageFile
。
我需要完全按照这样的方式执行此操作:在正文中发布带有文件的请求。
是否可以?我知道 HttpClient.PostAsync(..)
,但我不能将 StorageFile
放入请求正文中。我想发送 mp3
文件到 Web Api
在服务器端我得到这样的文件:
[System.Web.Http.HttpPost]
public HttpResponseMessage UploadRecord([FromUri]string filename)
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/Audio/" + filename + ".mp3");
postedFile.SaveAs(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
最佳答案
您可以使用 ByteArrayContent
类作为第二个参数将其作为 byte[]
发送:
StroageFile file = // Get file here..
byte[] fileBytes = null;
using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (DataReader reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
var httpClient = new HttpClient();
var byteArrayContent = new ByteArrayContent(fileBytes);
await httpClient.PostAsync(address, fileBytes);
关于c# - 通过 HttpClient.PostAsync 的 POST 请求,主体内有 StorageFile (WinRT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24112042/