[英]POST request via HttpClient.PostAsync with StorageFile inside body (WinRT)
我需要从 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);
如果您要上传任何可观大小的文件,那么最好使用后台传输 API,以便在应用程序暂停时上传不会暂停。 具体参见BackgroundUploader.CreateUpload ,它直接采用 StorageFile。 请参阅此关系的客户端和服务器端的后台传输示例,因为该示例还包括一个示例服务器。
要使用更少的内存,您可以直接将文件流通过管道传输到HttpClient
流。
public async Task UploadBinaryAsync(Uri uri)
{
var openPicker = new FileOpenPicker();
StorageFile file = await openPicker.PickSingleFileAsync();
if (file == null)
return;
using (IRandomAccessStreamWithContentType fileStream = await file.OpenReadAsync())
using (var client = new HttpClient())
{
try
{
var content = new HttpStreamContent(fileStream);
content.Headers.ContentType =
new HttpMediaTypeHeaderValue("application/octet-stream");
HttpResponseMessage response = await client.PostAsync(uri, content);
_ = response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
// Handle exceptions appropriately
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.