MVC的的文件下载如何实现

LC1990313 2012-06-27 09:02:26
上网搜了搜 以前WebForm的好多方法都不支持了!还有控件,相问问有没有什么方法能实现
我自己也写了一个,在Controller中写了一个把文件下载到本地的方法带有2个参数 文件名和路径
然后再View中的一个超链接想调用这个方法,就是点超链接然后下载!可是 最后那个下载路径完全乱套了!
...全文
279 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
仙剑 2012-06-27
  • 打赏
  • 举报
回复
给你看一下我以前做的一个MVC文件下载:
Controller:


/// <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;
}


View中用超链接指向这个Controller就行了,我是在js脚本中创建超链接的:

obj_td_title.innerHTML = '<a class="index_page_icon2" href="../Download.ashx/DownloadFile?doc_serial_no=' + jsonDoc[i].Serial_No +
'" target="_blank" title="' + jsonDoc[i].Description + '">' + jsonDoc[i].Name + '</a>';

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧