简体   繁体   English

使用.NET为Windows Store Apps上传文件

[英]Upload File with .NET for Windows Store Apps

Now that I have come to the realization that I can not use the normal .NET to write my Windows Store apps, I am trying to wade through the mess that is .NET for Windows Store apps. 既然我已经意识到我无法使用普通的.NET编写我的Windows Store应用程序,那么我正试图解决Windows Store应用程序.NET的混乱局面。 My latest discovery is that the System.Net.WebClient class is missing, and I needed to use it to upload a file. 我的最新发现是缺少System.Net.WebClient类,我需要使用它来上载文件。 Had this class been there, I would have done something along the lines of: 如果上过这个课,我会按照以下方式做一些事情:

webClient.UploadFile("http://my.website/upload.php?a=" + someParam, "POST", filepath);

Unfortunately, I can't do this in .NET for windows store. 不幸的是,我无法在用于Windows存储的.NET中执行此操作。 How would I achieve a similar functionality using only .NET for windows store? 如何仅使用.NET for Windows store实现类似的功能?

我会尝试HttpClient类-http: //msdn.microsoft.com/zh-cn/library/system.net.http.httpclient.aspx-它具有Post方法,如果您查看此答案,请在此处输入链接描述 ,它显示了如何为文件上传创建多部分数据。

You first need to get reference to a StorageFile . 您首先需要获得对StorageFile引用。 Using FileOpenPicker would be one way: 使用FileOpenPicker是一种方法:

var filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add(".txt");
var file = await filePicker.PickSingleFileAsync();

Then use the following code to upload the file (I haven't tried it as I don't have an upload page handy, but it should work): 然后使用以下代码上传文件(我没有尝试过,因为我没有方便的上传页面,但是应该可以使用):

using (var randomStream = (await file.OpenReadAsync()))
{
    using (var stream = randomStream.AsStream())
    {
        using (var content = new StreamContent(stream))
        {
            var httpClient = new HttpClient();
            await httpClient.PostAsync(uri, content);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM