【问题标题】:how to post string to URL in UWP如何在 UWP 中将字符串发布到 URL
【发布时间】:2017-09-26 12:25:36
【问题描述】:

我想将字符串发布到 URL 以便我可以上传文件。 我在 WPF 项目中做到了,我想在 UWP 项目中做到这一点。 这是我在 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类吗?
  • 这个问题很难理解。你到底在问什么? -1
  • 我想将一个字符串发送到一个 url,以便我可以将文件上传到服务器我在 WPF 项目中按照我维护的方式进行操作,我想在 UWP 项目中进行操作,但我没有做到所以..
  • @FlorianMoser 我尝试了很多解决方案,但没有任何效果
  • 也许可以向我们展示您迄今为止在 UWP 中所做的尝试,并展示您如何在端点中接收文件。

标签: c# wpf visual-studio uwp httprequest


【解决方案1】:

您可以上传带有HttpClient 的文件(它替换了UWP 中的WebClient

代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 2016-10-16
    • 2011-09-24
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多