C#实现文件下载

时间:2023-01-27 09:39:03
public ActionResult ExportShareStockExcelTemplate()
        {

            if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts) && !_permissionService.Authorize(StandardPermissionProvider.ManageVendorProducts))
                return AccessDeniedView();

            string filePath = Server.MapPath("~/Administration//Template//ProductMultiStoreShareStockTemplate.xlsx");
            string fileName = "ProductMultiStoreShareStockTemplate.xlsx"; //客户端保存的文件名            
            
            //以字符流的形式下载文件
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition",
                "attachment;  filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            return RedirectToAction("ListForStore");

        }
前臺按鈕:<a href="@Url.Action("ExportShareStockExcelTemplate")" class="k-button">下載導入範本</a>