Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
245 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can upload a file with the HttpClient (which replaces the WebClient in UWP)

Code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...