Upload File with .NET for Windows Store Apps

穿精又带淫゛_ 提交于 2019-12-24 15:40:03

问题


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. My latest discovery is that the System.Net.WebClient class is missing, and I needed to use it to upload a file. 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. How would I achieve a similar functionality using only .NET for windows store?


回答1:


I'd try HttpClient class - http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx - it has Post method, and if you look at this answerenter link description here, it shows how to create multipart data for file upload.




回答2:


You first need to get reference to a StorageFile. Using FileOpenPicker would be one way:

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);
        }
    }
}


来源:https://stackoverflow.com/questions/15602700/upload-file-with-net-for-windows-store-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!