asp.net文件下载
.aspx代码如下:
<%@ Page Title="" Language="C#" MasterPageFile="~/SAMPLE_CODE/AMST_SAMPLE.master" AutoEventWireup="true" CodeFile="S6_downloadLink.aspx.cs" Inherits="SAMPLE_CODE_S8_downloadLink" %> <asp:Content ID="Content1" ContentPlaceHolderID="CPH_HEAD" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="CPH_MEMO" Runat="Server"> <ul> <li>普通的超链接 <a>有时无法满足下载的需求,而是用浏览器直接打开了文件</li> </ul> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="CPH_MAIN" Runat="Server"> <p>普通超链接链接一个图片文件[直接打开]: <a href="../imgs/img1.jpg"> <a href="../imgs/img1.jpg"/> </a></p> <p>普通超链接链接一个rar文件[下载]: <a href="../imgs/temp.rar"> <a href="../imgs/temp.rar"/> </a> </p> <p>普通超链接指向一个wav文件[插件或运行环境不同而决定是打开还是下载]: <a href="../imgs/music1.wav"> <a href="../imgs/music1.wav"/> </a></p> <p>带有[download]属性的超链接-> 图片 <a href="../imgs/img1.jpg" download="myImg.jpg">图片下载</a> </p> <p style="font-size:16px; color:Red;">完全不暴露目标文件的下载LinkButton <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">图片文件下载</asp:LinkButton> </p> </asp:Content>
.aspx.cs代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class SAMPLE_CODE_S8_downloadLink : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void LinkButton1_Click(object sender, EventArgs e) { string fileName = "tempImg.jpg"; string filePath = Server.MapPath("~/imgs/img3.jpg"); Response.Clear(); Response.Buffer = true; Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.ContentType = "application/unknow"; Response.TransmitFile(filePath); Response.End(); } }
运行效果如下:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。