如何在UWP中将字符串发布到URL [英] how to post string to URL in UWP
本文介绍了如何在UWP中将字符串发布到URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个字符串发布到URL,以便我可以上传文件.我在WPF项目中做到了,我想在UWP项目中做到.这是我在WPF中的方法:
i want to post a string to an URL so that i can upload a file. I did it in WPF project and i want to do it in UWP project. this is my method in WPF:
OpenFileDialog ofd = new OpenFileDialog();
string url = "http://localhost/visualStudioUpload/upload1.php ";
WebClient Client = new WebClient();
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
byte[] byteArray = Client.UploadFile(url, "POST", ofd.FileName);
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
// dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
推荐答案
您可以使用 HttpClient
(在UWP中替换 WebClient
)上传文件
You can upload a file with the HttpClient
(which replaces the WebClient
in UWP)
代码:
private async Task<string> UploadImage(byte[] file, Uri url)
{
using (var client = new HttpClient())
{
MultipartFormDataContent form = new MultipartFormDataContent();
var content = new StreamContent(new MemoryStream(file));
form.Add(content, "postname", "filename.jpg");
var response = await client.PostAsync(url, form);
return await response.Content.ReadAsStringAsync();
}
}
这篇关于如何在UWP中将字符串发布到URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文