下载文件

/// <summary>
/// 下载服务器本地路径文件
/// </summary>
/// <param name="filePath">相对路径</param>
public void WriteFile(string filePath)
{
try
{
string _pre_path = filePath;
filePath = Server.MapPath(filePath);
if (File.Exists(filePath))
{
FileInfo info = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=erweima.jpg");
Response.AddHeader("Content-Length", info.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(filePath);
Response.Flush();
Response.End();

}
}
catch (System.Threading.ThreadAbortException ex0) { }
catch (Exception ex1)
{ }
finally
{
HttpContext.Current.Response.Close();
}
}

/// <summary>
/// 下载网络路径图片
/// </summary>
/// <param name="url">网络路径</param>
public void WriteFileUrl(string url)
{


Bitmap img = null;
System.Uri httpUrl = new System.Uri(url);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(httpUrl);

req.ServicePoint.Expect100Continue = false;

req.Method = "GET";

req.KeepAlive = true;

req.ContentType = "image/*";

HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

System.IO.Stream stream = null;
System.IO.MemoryStream ms = new MemoryStream();

try
{

stream = rsp.GetResponseStream();
img = new Bitmap(rsp.GetResponseStream());
//img.Save(@"E:/" + DateTime.Now.ToFileTime().ToString() + ".png");
img.Save(ms, ImageFormat.Png);

HttpContext curContext = HttpContext.Current;
curContext.Response.ContentType = "application/octet-stream";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode("erweimaqiye.jpg", Encoding.UTF8));
curContext.Response.BinaryWrite(ms.ToArray());
curContext.Response.End();

}
catch (System.Threading.ThreadAbortException ex0)
{ }
catch (Exception ex1)
{ }
finally
{

if (stream != null) { stream.Dispose(); stream.Close(); }

if (rsp != null) { rsp.Close(); }

if (ms != null) { ms.Dispose(); ms.Close(); }

}

}

posted on 2019-01-06 18:04  gfbppy  阅读(100)  评论(0编辑  收藏  举报

导航