我需要从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;
}
答案 0 :(得分:1)
您可以使用byte[]
类作为第二个参数将其作为ByteArrayContent
发送:
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);
答案 1 :(得分:0)
如果您要上传任意大小的文件,那么最好使用后台传输API,以便在应用暂停时上传不会暂停。具体请参见直接接收StorageFile的BackgroundUploader.CreateUpload。有关此关系的客户端和服务器端,请参阅Background Transfer sample,因为该示例还包括示例服务器。
答案 2 :(得分:0)
要使用更少的内存,您可以直接将文件流通过管道传输到 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
}
}
}