从HttpClient获取图片

问题描述 投票:0回答:3

我需要帮助从网络服务检索图片。这是一个 GET 请求。

目前我正在检索响应,并且可以将其转换为字节数组,这就是我想要的,但字节数组会使应用程序崩溃,所以我认为内容设置不正确。

我尝试使用以下方式设置响应内容:

response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };     

即使我的猜测是它设置错误,或者它在 requestHeader 中设置错误。

有什么想法吗?

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(baseurl.uri);
    client.DefaultRequestHeaders.Add("x-access-token", sessionToken);
    client.DefaultRequestHeaders
          .Accept
          .Add(new MediaTypeWithQualityHeaderValue("image/jpeg")
            );

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "");
    try
    {
        Task<HttpResponseMessage> getResponse = client.SendAsync(request);
        HttpResponseMessage response = new HttpResponseMessage();
        response = await getResponse;           
         //1. response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
        //2. response.Content.Headers.ContentType =

       //new MediaTypeHeaderValue("image/jpeg");//("application/octet-stream");


        byte[] mybytearray = null;
        if (response.IsSuccessStatusCode)
        {
        //3.
            mybytearray = response.Content.ReadAsByteArrayAsync().Result;
        }

        var responseJsonString = await response.Content.ReadAsStringAsync();
        System.Diagnostics.Debug.WriteLine(responseJsonString);
        System.Diagnostics.Debug.WriteLine("GetReportImage ReponseCode: " + response.StatusCode);
        return mybytearray;//{byte[5893197]}
    }
    catch (Exception ex)
    {
        string message = ex.Message;
        return null;
    }
}
c# asp.net-web-api httpclient
3个回答
0
投票

您可以将图像的 valid 字节数组作为

HttpContent

的一部分发送
 HttpContent contentPost = new 
    StringContent(JsonConvert.SerializeObject(YourByteArray), Encoding.UTF8,
    "application/json");

反序列化结果后,您可以检索字节数组,以与 jpeg 或任何其他格式相同的方式保存。

byte[] imageByteArray = byteArray;

using(Image image = Image.FromStream(new MemoryStream(imageByteArray)))
{
    image.Save("NewImage.jpg", ImageFormat.Jpeg); 
}

0
投票

如果您不需要验证文件,您可以像任何其他类型的文件一样获取图片

using var httpClient = new HttpClient();
var streamGot = await httpClient.GetStreamAsync("domain/image.png");
await using var fileStream = new FileStream("image.png", FileMode.Create, FileAccess.Write);
streamGot.CopyTo(fileStream);

-1
投票

这是一个简单的演示 UWP 应用程序,用于下载图像文件。 只需粘贴图像 URL 链接并按下载按钮即可下载所需的图像文件。

主页.xaml

<Page
    x:Class="HttpDownloader.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HttpDownloader"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <StackPanel>
            <TextBox x:Name="uriInput"
                     Header="URI:" PlaceholderText="Please provide an uri"
                     Width="300"
                     HorizontalAlignment="Center"/>
            <Button Content="Dowload"
                    HorizontalAlignment="Center"
                    Click="Button_Click"/>
        </StackPanel>
    </Grid>
</Page>

MainPage.xaml.xs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Net.Http;
using System.Net;
using Windows.Storage.Streams;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.Graphics.Imaging;
using System.Threading;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace HttpDownloader
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            HttpClient client = new HttpClient();
            string imageUrl = uriInput.Text;
            try
            {
                using (var cancellationTokenSource = new CancellationTokenSource(50000))
                {
                    var uri = new Uri(WebUtility.HtmlDecode(imageUrl));
                    using (var response = await client.GetAsync(uri, cancellationTokenSource.Token))
                    {
                        response.EnsureSuccessStatusCode();
                        var mediaType = response.Content.Headers.ContentType.MediaType;
                        string fileName = DateTime.Now.ToString("yyyyMMddhhmmss");
                        if (mediaType.IndexOf("jpg", StringComparison.OrdinalIgnoreCase) >= 0
                            || mediaType.IndexOf("jpeg", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            fileName += ".jpg";
                        }
                        else if (mediaType.IndexOf("png", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            fileName += ".png";
                        }
                        else if (mediaType.IndexOf("gif", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            fileName += ".gif";
                        }
                        else if (mediaType.IndexOf("bmp", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            fileName += ".bmp";
                        }
                        else
                        {
                            fileName += ".png";
                        }

                        // Get the app's local folder.
                        StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

                        // Create a new subfolder in the current folder.
                        // Replace the folder if already exists.
                        string desiredName = "Images";
                        StorageFolder newFolder = await localFolder.CreateFolderAsync(desiredName, CreationCollisionOption.ReplaceExisting);
                        StorageFile newFile = await newFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                        using (Stream streamStream = await response.Content.ReadAsStreamAsync())
                        {
                            using (Stream streamToWriteTo = File.Open(newFile.Path, FileMode.Create))
                            {
                                await streamStream.CopyToAsync(streamToWriteTo);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occur");
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

您将在此文件夹中找到该图像。

Users/[current user name]/AppData/Local/Packages/[Application package name]/LocalState/Images

© www.soinside.com 2019 - 2024. All rights reserved.