2

我需要POST来自 WinRT 应用程序的创建请求,该请求应包含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;
        }
4

3 回答 3

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);
于 2014-06-09T00:28:49.753 回答
0

如果您要上传任何大小合适的文件,那么最好使用后台传输 API,以便在应用程序暂停时上传不会暂停。具体参见BackgroundUploader.CreateUpload直接采用 StorageFile。请参阅此关系的客户端和服务器端的后台传输示例,因为该示例还包括一个示例服务器。

于 2014-06-09T16:14:04.207 回答
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
            }
        }
    }
于 2021-01-20T09:19:00.133 回答