【问题标题】:WebClient DownloadFile downloads corrupt jpeg for redirected URI'sWebClient DownloadFile 为重定向的 URI 下载损坏的 jpeg
【发布时间】:2013-11-19 04:35:17
【问题描述】:

我在使用 WebClient 类下载 jpeg 图像时遇到了一些问题。我正在尝试通过以下代码下载 jpeg 图片:

public bool DownloadUri(string strUri, string destPath)
{
    bool result = false;
    try
    {
        Uri uri = new Uri(strUri, UriKind.RelativeOrAbsolute);
        WebClient client = new WebClient();
        client.DownloadFile(uri, destPath);
        result = true;
    }
    catch (Exception ex)
    {
        result = false;
    }
    return result;
}       

大多数工作正常,但当 jpeg 不存在时,我尝试下载的站点会重定向并且下载不会引发异常,它会下载大小仅为 8k 的损坏 jpeg。这是我提供的一个违规网址:

http://axisproperty.net.au/Upload/listing/500748870/500748870_1_500266205%2c1336368187%2cImageA.jpg

我已经使用 Uri.TryCreate 和 Uri.IsWellFormedUriString(urlAttribute.Value, UriKind.Absolute) 验证了 uri。我尝试执行 File.Exists(uri.ToString()) 来验证 uri 是否具有与其关联的有效文件,尽管即使对于有效的 url 也会失败。

有没有其他方法可以验证文件确实存在,这样我就不会下载所有这些不必要的损坏 jpeg 文件?

【问题讨论】:

    标签: .net file download webclient


    【解决方案1】:

    webclient.downloadfile 方法不处理 http 重定向

    你应该为此使用 webrequest

    public static int DownloadFile(String remoteFilename, String localFilename)
        {
          // Function will return the number of bytes processed
          // to the caller. Initialize to 0 here.
          int bytesProcessed = 0;
    
          // Assign values to these objects here so that they can
          // be referenced in the finally block
          Stream remoteStream = null;
          Stream localStream = null;
          WebResponse response = null;
    
          // Use a try/catch/finally block as both the WebRequest and Stream
          // classes throw exceptions upon error
          try
          {
            // Create a request for the specified remote file name
            WebRequest request = WebRequest.Create(remoteFilename);
            if (request != null)
            {
              // Send the request to the server and retrieve the
              // WebResponse object 
              response = request.GetResponse();
              if (response != null)
              {
                // Once the WebResponse object has been retrieved,
                // get the stream object associated with the response's data
                remoteStream = response.GetResponseStream();
    
                // Create the local file
                localStream = File.Create(localFilename);
    
                // Allocate a 1k buffer
                byte[] buffer = new byte[1024];
                int bytesRead;
    
                // Simple do/while loop to read from stream until
                // no bytes are returned
                do
                {
                  // Read data (up to 1k) from the stream
                  bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
    
                  // Write the data to the local file
                  localStream.Write(buffer, 0, bytesRead);
    
                  // Increment total bytes processed
                  bytesProcessed += bytesRead;
                } while (bytesRead > 0);
              }
            }
          }
          catch (Exception e)
          {
            Console.WriteLine(e.Message);
          }
          finally
          {
            // Close the response and streams objects here 
            // to make sure they're closed even if an exception
            // is thrown at some point
            if (response != null) response.Close();
            if (remoteStream != null) remoteStream.Close();
            if (localStream != null) localStream.Close();
          }
    
          // Return total bytes processed to caller.
          return bytesProcessed;
        }
    

    【讨论】:

      【解决方案2】:

      对不起,我应该更清楚。我提供的 url 无效,因此重定向到未找到页面或类似页面,因此在这种情况下,我不想下载,因为该文件中没有有效的 jpeg 图像。我找到了以下解决方案:

      public static bool CheckURL(string URL)
      {
          try
          {
              HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
              req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
              using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse())
              {
                  if ((rsp.StatusCode == HttpStatusCode.OK) && rsp.ContentType.ToLower() == "image/jpeg")
                  {
                      return true;
                  }
              }
          }
          catch
          {
              return false;
          }
          return false;
      }   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-26
        • 1970-01-01
        相关资源
        最近更新 更多