3,242
社区成员
发帖
与我相关
我的任务
分享
public void OpenAttachment(string RootFolder, string SubFolder, string FileName, string DocName)
{
string url = "";
try
{
//Get the extension of File.
string[] fext = DocName.Split('.');
// Get the extension of File to determine the file type
string casestring = "";
if (fext.Length > 1)
{
casestring = fext[fext.Length - 1];
}
//set the content type of file according to extension
int flag = 0;
SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
string contentType = "";
url = SPContext.Current.Web.Url + "/" + RootFolder + "/" + SubFolder + "/" + FileName + "." + casestring;
SPFile tempFile = web.GetFile(url);
byte[] obj = (byte[])tempFile.OpenBinary();
switch (casestring)
{
case "txt":
contentType = "text/plain";
break;
case "htm": contentType = "text/html";
break;
case "html": contentType = "text/html";
break;
case "rtf": contentType = "text/richtext";
break;
case "jpg": contentType = "image/jpeg";
break;
case "jpeg": contentType = "image/jpeg";
break;
case "gif": contentType = "image/gif";
break;
case "bmp": contentType = "image/bmp";
break;
case "mpg": contentType = "video/mpeg";
break;
case "mpeg": contentType = "video/mpeg";
break;
case "avi": contentType = "video/avi";
break;
case "pdf": contentType = "application/pdf";
break;
case "doc": contentType = "application/msword";
break;
case "dot": contentType = "application/msword";
break;
case "csv": contentType = "application/vnd.msexcel";
break;
case ".xls": contentType = "application/vnd.msexcel";
break;
case ".xlt": contentType = "application/vnd.msexcel";
break;
default: contentType = "application/octet-stream";
break;
}
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename= " + DocName);
HttpContext.Current.Response.ContentType = contentType;
//Check that the client is connected and has not closed the connection after the request
if (HttpContext.Current.Response.IsClientConnected)
HttpContext.Current.Response.BinaryWrite(obj);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}