110,534
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 下载文件,需传入Filename、Filepath,及Extension
/// </summary>
/// <returns></returns>
public ActionResult DownloadFile()
{
//判断用户是否登录
if (Session["user"] == null)
{
Response.Write("Sorry,please login");
return null;
}
try
{
if (CommonFunctions.CommonFunctions.hasSecurity(((User)Session["user"]).Role_id, 17))
{
string doc_serial_no = Request.QueryString["doc_serial_no"];
using (MDMSDBContext dbContext = new MDMSDBContext())
{
var js_record = from t_doc in dbContext.DsDocuments
join t_doc_type in dbContext.DsDocTypes on t_doc.Type_id equals t_doc_type.Id
where t_doc.Serial_No == doc_serial_no
select new
{
doc_name = t_doc.Name,
doc_path = t_doc.path,
doc_extention = t_doc_type.Extension_name
};
string filename = js_record.First().doc_name;
string filepath = js_record.First().doc_path;
string fileextension = js_record.First().doc_extention;
filepath = Server.MapPath(Request.ApplicationPath + "/Documents/") + filepath;
System.IO.FileStream r = new System.IO.FileStream(filepath, System.IO.FileMode.Open); //创建文件流读取要下载的文件
Response.Clear(); //清空响应流
Response.AddHeader("connection", "Keep-Alive");
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename) + "." + fileextension); //指定文件名
//Response.ContentType = fileextension; //
Response.AddHeader("Content-Length", r.Length.ToString()); //指定文件长度
while (true)
{
byte[] buffer = new byte[1024]; //开辟1024的缓冲区
int len = r.Read(buffer, 0, 1024);
if (len == 0) //到达文件末尾,跳出循环
{
break;
}
if (len == 1024) //读出的文件长度等于1024,就向客户端发送数据
{
Response.BinaryWrite(buffer);
}
else //如果小于1024,重新定义长度
{
byte[] b = new byte[len];
for (int i = 0; i < len; i++)
b[i] = buffer[i];
Response.BinaryWrite(b); //数据发送到客户端
}
}
r.Close(); //关闭流
Response.End(); //下载完成
updateDocument(doc_serial_no);
string log_content = "Download File Name:" + filename + "<br>";
CommonFunctions.CommonFunctions.writeOperationLog("Download File", "Download File", ((User)Session["user"]).Name, log_content);
}
}
else
{
Response.Write("You have no security to download this document!");
}
}
catch (Exception ex)
{
Response.Write("Sorry,download file error!<br>" + ex.ToString());
}
return null;
}