UWP如何从我的网络API下载图像?

时间:2018-05-09 05:28:55

标签: c# asp.net-core uwp httpclient

我有一个.NET Core Web应用程序,它在wwwroot文件夹中存储不同的目录。

Diagram

我想知道如何使用HttpClient API从我的UWP应用程序下载这些照片。提前谢谢。

1 个答案:

答案 0 :(得分:0)

  

我的意思是如何在UWP中实现代码以使用HttpClient下载这些文件

您可以使用HttpClient从服务器下载流。以下细分代码来自HttpClient官方代码示例。

private async void Start_Click(object sender, RoutedEventArgs e)
{
    Uri resourceAddress;

    // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
    // valid, absolute URI, we'll notify the user about the incorrect input.
    if (!Helpers.TryGetUri(AddressField.Text, out resourceAddress))
    {
        rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
        return;
    }

    Helpers.ScenarioStarted(StartButton, CancelButton, OutputField);
    rootPage.NotifyUser("In progress", NotifyType.StatusMessage);

    try
    {
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceAddress);

        // Do not buffer the response.
        HttpResponseMessage response = await httpClient.SendRequestAsync(
            request,
            HttpCompletionOption.ResponseHeadersRead).AsTask(cts.Token);

        OutputField.Text += Helpers.SerializeHeaders(response);

        StringBuilder responseBody = new StringBuilder();
        using (Stream responseStream = (await response.Content.ReadAsInputStreamAsync()).AsStreamForRead())
        {
            int read = 0;
            byte[] responseBytes = new byte[1000];
            do
            {
                read = await responseStream.ReadAsync(responseBytes, 0, responseBytes.Length);

                responseBody.AppendFormat("Bytes read from stream: {0}", read);
                responseBody.AppendLine();

                // Use the buffer contents for something. We can't safely display it as a string though, since encodings
                // like UTF-8 and UTF-16 have a variable number of bytes per character and so the last bytes in the buffer
                // may not contain a whole character. Instead, we'll convert the bytes to hex and display the result.
                IBuffer responseBuffer = CryptographicBuffer.CreateFromByteArray(responseBytes);
                responseBuffer.Length = (uint)read;
                responseBody.AppendFormat(CryptographicBuffer.EncodeToHexString(responseBuffer));
                responseBody.AppendLine();
            } while (read != 0);
        }
        OutputField.Text += responseBody.ToString();

        rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
    }
    catch (TaskCanceledException)
    {
        rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
    }
    catch (Exception ex)
    {
        rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage);
    }
    finally
    {
        Helpers.ScenarioCompleted(StartButton, CancelButton);
    }
}

您也可以使用Background Transfer来实现这一目标。这是official code sample

private async void StartDownload(BackgroundTransferPriority priority)
{
    // Validating the URI is required since it was received from an untrusted source (user input).
    // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
    // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
    // the "Home or Work Networking" capability.
    Uri source;
    if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out source))
    {
        rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
        return;
    }

    string destination = fileNameField.Text.Trim();

    if (string.IsNullOrWhiteSpace(destination))
    {
        rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage);
        return;
    }

    StorageFile destinationFile;
    try
    {
        destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
            destination,
            CreationCollisionOption.GenerateUniqueName);
    }
    catch (FileNotFoundException ex)
    {
        rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage);
        return;
    }

    BackgroundDownloader downloader = new BackgroundDownloader();
    DownloadOperation download = downloader.CreateDownload(source, destinationFile);

    Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}",
        source.AbsoluteUri, destinationFile.Name, priority, download.Guid));

    download.Priority = priority;

    // Attach progress and completion handlers.
    await HandleDownloadAsync(download, true);
}