UWP, как скачать изображение с моего веб-API? - PullRequest
0 голосов
/ 09 мая 2018

У меня есть .NET Core Web Application, которая хранит разные каталоги в папке wwwroot.

Diagram

Я хочу знать, как загрузить эти фотографии из моего приложения UWP с помощью HttpClient API. Заранее спасибо.

1 Ответ

0 голосов
/ 10 мая 2018

Я имею в виду, как реализовать коды в 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);
    }
}

И вы также можете использовать Фоновая передача , чтобы понять это.И это официальный пример кода .

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