天天看點

利用repeater綁定下載下傳位址并點選下載下傳(避免中文檔案名亂碼)

aspx       

             <asp:repeater id="repeater1" runat="server">

                        <headertemplate>

                            <table>

                                <tr>

                        </headertemplate>

                        <itemtemplate>

                            <tr>

                                <td style="border: 0px;">

                                    <a href='../download.ashx?url=<%# server.urlencode(eval

                                    ("filepath").tostring())%>'>

                                     <%#eval_r("filename")%></a>

                                </td>

                        </itemtemplate>

                        <footertemplate>

                            </tr></table></footertemplate>

                    </asp:repeater>

download.ashx

using system;

using system.collections;

using system.data;

using system.linq;

using system.web;

using system.web.services;

using system.web.services.protocols;

using system.xml.linq;

namespace web.ucenter

{

    /// <summary>

    /// $codebehindclassname$ 的摘要說明

    /// </summary>

    [webservice(namespace = "http://tempuri.org/")]

    [webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]

    public class download : ihttphandler

    {

        public void processrequest(httpcontext context)

        {

            try

            {

                string path = context.request.querystring["url"].tostring();

                system.io.fileinfo file = new system.io.fileinfo(path);

                context.response.clear();

                context.response.charset = "gb2312";

                context.response.contentencoding = system.text.encoding.utf8;

                // 添加頭資訊,為"檔案下載下傳/另存為"對話框指定預設檔案名

                context.response.addheader

                    ("content-disposition",

                    "attachment; filename="

                    +

                   system.web.httputility.urlencode

                (file.name,system.text.encoding.utf8));// 防止中文名有亂碼

                // 添加頭資訊,指定檔案大小,讓浏覽器能夠顯示下載下傳進度

                context.response.addheader("content-length", file.length.tostring());

                //// 指定傳回的是一個不能被用戶端讀取的流,必須被下載下傳

                //context.response.contenttype = "application/ms-excel";

                // 把檔案流發送到用戶端

                context.response.writefile(file.fullname);

                // 停止頁面的執行

                context.response.end();

            }

            catch

                context.response.write("您下載下傳的資源不存在!");

        }

        public bool isreusable

            get

                return false;

    }

}

注意點:我在資料庫存儲的檔案路徑是加server.map的絕對路徑。實際下載下傳的時候根據實際情況修改代碼。