生成图片的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);
似乎不起作用,不知道什么原因。
已经解决。
其实主要是让浏览器直接下载文件而不是打开文件。
要做两步。
一就是把响应头的类型设置成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());
string fileName = "aaa.txt";//客户端保存的文件名
string filePath = Server.MapPath("DownLoad/aaa.txt");//路径
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();