.Net MVC FTP文件下载

来源:互联网 发布:华傲数据是外包公司么 编辑:程序博客网 时间:2024/06/08 10:35

前台通过<a>标签实现文件下载:

代码为:

1 window.open("/home/downloadAttachfile?filename=" + "文件名称");

效果为打开新的tab页面实现下载;

后台HomeController处理请求:

 1  public FileContentResult downloadAttachfile() 2         { 3             string ftpServerIP = asolution.config.Object.FileServers.FindByName("ftp").Host; //本次项目框架web.config的FTP的ip和用户名,密码配置信息 4             string ftpUserID = asolution.config.Object.FileServers.FindByName("ftp").Uid; 5             string ftpPassword = asolution.config.Object.FileServers.FindByName("ftp").Pwd; 6             string fileName = Server.UrlDecode(Request.Params["filename"]); 7             string uri = ftpServerIP + "/attachFiles/" + fileName; 8             Uri serverUri = new Uri(uri); 9 10             // Get the object used to communicate with the server.11             WebClient request = new WebClient();12 13             // This example assumes the FTP site uses anonymous logon.14             request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);15             byte[] newFileData;16             try17             {18                 newFileData = request.DownloadData(serverUri.ToString()); //从FTP服务器下载文件19                 string fileString = System.Text.Encoding.UTF8.GetString(newFileData);20                 Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));21                 string fileType = fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - 1 - fileName.LastIndexOf('.'));23                 string contenttype = "application/";24                 if (fileType == ".text")   //根据文件类型判断类型头25                 {26                     contenttype = "text/plain";27                 }28                 else if (fileType == ".doc" || fileType == ".docx")29                 {30                     contenttype += "msword";31                 }32                 else if (fileType == ".xls" || fileType == ".xlsx" || fileType == ".ppt" || fileType == ".pptx")33                 {34                     contenttype = contenttype + "x-" + fileType.Substring(1);35                 }36                 else if (fileType == ".jpg" || fileType == "bmp" || fileType == "jpeg" || fileType == "gif" || fileType == "png")37                 {38                     contenttype = "image/" + fileType.Substring(1);39                 }40                 else41                 {42                     contenttype += "x-" + fileType.Substring(1);43 44                 }45                 return File(newFileData, contenttype);46             }47             catch (WebException e)48             {49                 // 若服务器未开启或者文件不存在抛出异常50                 Response.Write("<script languge='javascript'>alert('源文件已经被删除或者文件服务器未开启!'); window.close(); </script>");51                 return null;52             }53         }

 

0 0
原创粉丝点击