无法从服务器获取完整图像

时间:2014-09-30 13:57:40

标签: c# .net winforms

我有一个C#windows表单应用程序从url(asp.net应用程序)下载文件但它没有返回完整图像让我们说图像是780kb,windows表单创建的文件正好是381字节。

我无法弄清楚这个问题。请帮忙。

我用于下载的代码是:

 public bool getFileFromURL(string url, string filename)
        {
            long contentLength = 0;
            Stream stream = null;
            try
            {
                WebRequest req = WebRequest.Create(url);
                WebResponse response = req.GetResponse();
                stream = response.GetResponseStream();
                contentLength = response.ContentLength;


                // Transfer the file
                byte[] buffer = new byte[10 * 1024]; // 50KB at a time
                int numBytesRead = 0;
                long totalBytesRead = 0;
                using (FileStream fileStream = new FileStream(filename, FileMode.Create))
                {
                    using (BinaryWriter fileWriter = new BinaryWriter(fileStream))
                    {
                        while (stream.CanRead)
                        {
                            numBytesRead = stream.Read(buffer, 0, buffer.Length);
                            if (numBytesRead == 0) break;
                            totalBytesRead += numBytesRead;
                            fileWriter.Write(buffer, 0, numBytesRead);
                        }
                        fileWriter.Close();
                    }
                    fileStream.Close();
                }
                stream.Close();
                response.Close();
                req.Abort();

                return true;

            }
            catch (Exception)
            {

                return false;
            }



        }

这是我的asp.net应用代码:

   using (PortalEntities db = new PortalEntities())
        {
                PortalModel.Command command = db.Commands.SingleOrDefault(c => c.id == id);

                var filePath = Server.MapPath("~/Uploads/"+command.arguments);
                if (!File.Exists(filePath))
                    return;

                var fileInfo = new System.IO.FileInfo(filePath);
                Response.ContentType = "image/jpg";
                Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.WriteFile(filePath);
                Response.End();
        }

3 个答案:

答案 0 :(得分:1)

从Web响应中将一些字节写入文件是一个非常多的代码。这样的事情(.NET 4 +):

public static bool GetFileFromURL(string url, string filename)
{
    try
    {
        var req = WebRequest.Create(url);
        using (Stream output = File.OpenWrite(filename))
        using (WebResponse res = req.GetResponse())
        using (Stream s = res.GetResponseStream())
            s.CopyTo(output);
        return true;
    }
    catch
    {
        return false;
    }
}

答案 1 :(得分:0)

您可以更优雅的方式下载图片,之前已在此处讨论Unable to locate FromStream in Image class

并使用File.WriteAllBytes方法将字节数组保存为文件,更多信息请参阅 http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes(v=vs.110).aspx

因此,所有客户端代码都可以替换为

public void getFileFromURL(string url, string filename)
{
    using (var webClient = new WebClient())
    {
        File.WriteAllBytes(filename,webClient.DownloadData(url));
    }
}

答案 2 :(得分:0)

老兄,你为什么不使用WebClient.DownloadFileAsync?

private void DownloadFile(string url, string path)
{
    using (var client = new System.Net.WebClient())
    {
        client.DownloadFileAsync(new Uri(url), path);
    }
}

这就是它,但这种方法无法下载2GB以上。但我不认为图像是那么大的xD。

希望它有所帮助!