/// <summary>
/// 文档库文档复制,获取文件
/// </summary>
public void DownloadFile()
{
try
{
string IDstr = this.Request["id"];//文档ID
int ID = 0;
bool IsId = int.TryParse(IDstr, out ID);
if (IsId)
{
string curDocLibUrl = "/Template/TemplateDocument/";//当前文档所在文档库
SPSecurity.RunWithElevatedPrivileges(delegate()
{
Guid siteID = Web.Site.RootWeb.Site.ID;
using (SPSite spSite = new SPSite(siteID))
{
using (SPWeb spWeb = spSite.AllWebs["Template"])
{
spWeb.AllowUnsafeUpdates = true;
SPList clist = spWeb.GetList(curDocLibUrl);
SPListItem item = clist.GetItemById(ID);
if (item != null)
{
SPFile file = item.File;
string fn = System.IO.Path.GetFileName(file.Name);
byte[] contet = file.OpenBinary();
ExportByWeb(contet, fn);//下载文件
Stream ss = file.OpenBinaryStream();
WriteFile(fn, ss);//将文件保存到服务器对应路径下
}
}
}
});
}
}
catch (Exception ex)
{
this.DebugTrace("te DownloadFile failed: {0}", ex.Message);
}
}
/// <summary>
/// 下载文档
/// </summary>
/// <param name="buffer"></param>
/// <param name="strFileName"></param>
public static void ExportByWeb(byte[] buffer, string FileName)
{
HttpContext curContext = HttpContext.Current;
// 设置编码和附件格式
curContext.Response.ContentType = "application/octet-stream";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AddHeader("Content-Length", buffer.Length.ToString());
curContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8));
curContext.Response.Clear();
curContext.Response.BinaryWrite(buffer);
curContext.Response.Flush();
curContext.Response.End();
}
/// <summary>
/// 将文件保存到服务器对应路径下
/// </summary>
/// <param name="fn">文件名带后缀</param>
/// <param name="Strings">文件流</param>
/// <param name="IDstr">文件ID</param>
public static void WriteFile(string fn, Stream Strings)
{
string Path = @"C:\test\downfile\" + fn;
if (!File.Exists(Path))
{
FileStream f = File.Create(Path);
f.Close();
f.Dispose();
}
StreamWriter f2 = new StreamWriter(Path, true, Encoding.UTF8);
f2.WriteLine(Strings);
f2.Close();
f2.Dispose();
}
#endregion
前台页面切记不要用ajax请求去下载文件,否则会下载不成功的,只能获取到流数据。可以通过链接去打开页面下载
HttpContext curContext = HttpContext.Current;
curContext.Response.Redirect("http://xxx.xxx.xx.xx?id=3&action=downloadfile");