C#如何通过URL下载图片?

生成图片的URL假设是这样:http://localhost/administrator/qrcode.aspx?pid=78

qrcode.aspx.cs的生成图片的部分代码:

Image image = new Bitmap(200, 200);
Graphics g = Graphics.FromImage(image);
try
{
  string url="http://localhost";

  DotNetBarcode bc = new DotNetBarcode();
  bc.Type = DotNetBarcode.Types.QRCode;
  bc.PrintCheckDigitChar = true;
  bc.WriteBar(url, 0, 0, 210, 210, g);

  System.IO.MemoryStream ms = new System.IO.MemoryStream();
  image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

  Response.ClearContent();
  Response.ContentType = "image/Png";

  Response.BinaryWrite(ms.ToArray());
  ms.Dispose();
}
finally
{
  g.Dispose();
  image.Dispose();
}

现在如果我要输入http://localhost/administrator/qrcode.aspx?pid=78&download=true就下载图片到本地要怎么做?


找过一些资料,WebClient.DownloadFile方法不知道怎么用。满足参数download=true的时候使用Image.Save(string filename, ImageFormat format);似乎不起作用,不知道什么原因。

阅读 26.5k
2 个回答

已经解决。
其实主要是让浏览器直接下载文件而不是打开文件。
要做两步。
一就是把响应头的类型设置成application/octet-stream
二就是设置HTTP响应头的名字为Content-Disposition,设定值为attachment; filename=theFilename。这里的theFileName就是文件下载对话框里面的默认文件名。

Response.ClearContent();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode("qrcode.png", System.Text.Encoding.UTF8));
Response.BinaryWrite(ms.ToArray());
public void DoGetImage(string url, string path)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

    req.ServicePoint.Expect100Continue = false;
    req.Method = "GET";
    req.KeepAlive = true;

    req.ContentType = "image/png";
    HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

    System.IO.Stream stream = null;

    try
    {
        // 以字符流的方式读取HTTP响应
        stream = rsp.GetResponseStream();
        Image.FromStream(stream).Save(path);
    }
    finally
    {
        // 释放资源
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Microsoft
子站问答
访问
宣传栏