这里先说下载文件
<a style="color:black; margin-right:3px;" onclick="dowAtt(' + index + ')" ><i class="fa fa-book"></i>查看附件</a>
function dowAtt(i) { var rows = $("#orderGrid").datagrid("getRows"); if (rows[i].LogisticsAtt != null) { window.location.href = "/Admin/Account/Download?filePath=" + rows[i].LogisticsAtt; } else { layer.msg("服务器暂未查找到该附件!"); } }
/// <summary> /// 下载 /// </summary> /// <returns></returns> [HttpGet] public ActionResult Download() { string filePath = Server.MapPath(Request.Params["filePath"]); //文件路径 string fileName = filePath.Substring(filePath.LastIndexOf('\\') + 1); //文件名 byte[] bytes = null; try { FileStream fs = new FileStream(filePath, FileMode.Open); bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); } catch (Exception e) { Response.Redirect("/Admin/Error/ServerError/1"); return View(); } Response.Charset = "utf-8"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); return new EmptyResult(); }
就这么简单,结合我前面的那一篇上传,你的上传下载就全部搞定了
这一part我要来说说mvc配置xml保护服务器文件不被url直接访问
在你需要受保护的文件夹里面新建一个Web.config(当然你要是全站都想保护的话,请忽略这一步,直接在最外面的web.config配置就行了
然后把你需要保护的后缀名加进来就行了
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <security> <requestFiltering> <fileExtensions> <add fileExtension=".png" allowed="false"/> <add fileExtension=".rar" allowed="false"/> <add fileExtension=".zip" allowed="false"/> <add fileExtension=".doc" allowed="false"/> <add fileExtension=".docx" allowed="false"/> <add fileExtension=".xls" allowed="false"/> <add fileExtension=".xlsx" allowed="false"/> <add fileExtension=".pdf" allowed="false"/> <add fileExtension=".swf" allowed="false"/> <add fileExtension="ceb" allowed="false"/> <add fileExtension=".7z" allowed="false"/> </fileExtensions> </requestFiltering> </security> </system.webServer> </configuration>
这样就行了,如果你在地址栏输入文件路径是会报404的错的。
---------------------------------------------------------------------------------------------------------
转载请记得说明作者和出处哦-.-
作者:KingDuDu
原文出处:https://www.cnblogs.com/kingdudu/articles/4765544.html
---------------------------------------------------------------------------------------------------------