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/

相关文章:

c# - Automapper - 如何从源子对象映射到目标

c# - 处理生产配置中的密码以进行自动化部署

c# - 在哪里可以找到有关 WM Windows 消息代码的信息?

c# - 对多个 WPF 控件应用类似的绑定(bind)

类型为 "application/x-www-form-urlencoded"的 C# HttpWebRequest - 如何在内容正文中发送 '&' 字符?

php - Wamp服务器错误消息: Undefined variable: _post?

c# - ResourceDictionary Source(通用 Windows 平台)中的 Uri 语法

c# - UWP 中的 Process.Start

javascript - 如何在 iframe 中发送表单?

xaml - GridView 水平滚动 (UWP)