c# - 通过 HttpClient.PostAsync 的 POST 请求,主体内有 StorageFile (WinRT)

标签 c# post uwp windows-runtime

我需要从 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/

相关文章:

visual-studio - 无法将 UWP 部署到本地计算机。 "The required framework CoreRuntime.1.0.appx failed to install"

c# - UWP Combobox SelectedItem 忽略其绑定(bind)值

c# - 如何将虚拟路径映射到物理路径?

c# - 使用正弦创建跳跃算法

Magento 支付模块,如 PayPal(外部 URL 重定向)

swift - Alamofire + 光泽 : nested JSON array not working

xaml - "TemplateBinding' 之后使用的 '{' 必须是标记扩展“UWP GridView 上的错误

c# - 故障响应包含一个字符串值,其中需要一个整数

c# - 如何找到圆的重叠部分

android - 通过 Retrofit 从内存上传位图