POST请求通过HttpClient.PostAsync与StorageFile内部的主体(WinRT)

本文关键字:内部 主体 WinRT StorageFile 请求 HttpClient PostAsync POST | 更新日期: 2023-09-27 18:07:54

我需要从WinRT应用程序创建POST请求,其中应包含StorageFile。我需要这样做的风格完全像这样:post请求与文件内体。这可能吗?我知道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;
        }

POST请求通过HttpClient.PostAsync与StorageFile内部的主体(WinRT)

您可以将其作为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);

如果你上传的文件相当大,那么最好使用后台传输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
            }
        }
    }