ASP.NET MVC 远程下载文件

直接看代码吧:

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="filePath">文件地址</param>
        /// <returns></returns>
        public ActionResult DownLoadFile(string filePath)
        {
            if (filePath == null)
            {
                return null;
            }
            //string UrlString = "http://123.123.123.123/abc/123.pdf";
            int startIndex = filePath.LastIndexOf("/");
            string fileName = filePath.Substring(startIndex + 1);
            byte[] fileData;
            try
            {
                WebRequest.Create(filePath);
            }
            catch (Exception ex)
            {
                //To do something
                return null;
            }
            try
            {
                using (WebClient client = new WebClient())
                {
                    fileData = client.DownloadData(filePath);
                    return File(fileData, "text/plain", fileName);
                }
            }
            catch (Exception ex)
            {
                //To do something
                return null;
            }
        }

 

posted @ 2016-03-04 09:05  我在赫尔辛基火车站  阅读(1058)  评论(0编辑  收藏  举报