为什么使用 HttpWebRequest 从本地主机下载的图像已损坏?

Why the downloaded image from localhost using HttpWebRequest corrupted?

原始图像(.jpg) 文件大小为49kb 但当我下载后文件大小为87kb 并且已损坏。但是对于文本文件,它是有效的。使用 HttpWebRequest 或其他 System.Net class 下载图像需要做什么? 我正在为本地主机使用 XAMPP。

//Usage: HttpDownload("http://www.localhost/files/imagine.jpg", "seo.jpg");

    static async void HttpDownload(string remoteFileOrUri, string localFileName)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(remoteFileOrUri));
        HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
        StreamReader rdr = new StreamReader(response.GetResponseStream());
        StreamWriter sw = new StreamWriter(File.OpenWrite(localFileName));

        sw.Write(rdr.ReadToEnd());
        sw.Flush();

        rdr.Close();
        sw.Close();
        Console.WriteLine("fin!");
    }

您不应将 StreamReader 和 StreamWriter 用于非文本内容。当您使用它们时,会应用编码。编码不能很好地与任意二进制数据混合,this blog 将证明这一点。

相反,您应该使用简单的 FileStream:

using (var output = File.OpenWrite(localFileName))
{
    using (var responseStream = response.GetResponseStream())
    {
        await responseStream.CopyToAsync(output);
    }
}

不幸的是,这可能不是您唯一的问题,因为 GZip 压缩(如果服务器正在使用它)也可能会出现问题。您可以通过简单的设置更改来解决这个问题:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(remoteFileOrUri));

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

using (var output = File.OpenWrite(localFileName))
{
    using (var responseStream = response.GetResponseStream())
    {
        await responseStream.CopyToAsync(output);
    }
}