首页 > 代码库 > asp.net文件下载

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=http://www.mamicode.com/"../imgs/img1.jpg">>
.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();

    }

}

运行效果如下:


asp.net文件下载