ASP.NET 利用伺服器控制項上傳和下載檔案

來源:互聯網
上載者:User

asp教程.net 利用伺服器控制項上傳和下載檔案

第一步,選擇上傳檔案。每二步,判斷檔案格式。第三步,指定存放目錄,第四步,儲存檔案。

 

廢話不多說直接上菜:

   

 <asp:fileupload id="fileupload" style="border: solid 1px #a5d0f3;" width="300px" runat="server" />

        <asp:button id="btnupload" runat="server" text="上傳檔案" onclick="btnupload_click" onclientclick="return fun_checktype();" />

 

        <script type="text/網頁特效">

            function fun_checktype() {

            var filename = document.getelementbyid("fileupload").value;

 

            if (filename == "") {

                alert("請選擇上傳的檔案!");

                return false;

            }

 

            var seat = filename.lastindexof(".");

            var extension = filename.substring(seat).tolowercase();

            //設定格式

            var allowed = [".jpg", ".gif", ".png", ".bmp", ".jpeg", ".sql", ".txt", ".doc", ".xls"];

 

            for (var i = 0; i < allowed.length; i++) {

                if (!(allowed[i] != extension)) {

                     return true;

                 }

             }

 

            alert("不支援" + extension + "格式!");

            return false;

            }

        </script>

 

源碼很乾淨簡單,就不多做解釋,需要注意一點的是按鈕的用戶端點擊事件:onclientclick

 

好了,涼菜已經上桌了,現在開始上主菜。 

 

protected void btnupload_click(object sender, eventargs e)

    {

        //指定檔案存放目錄,這裡有個條件伺服器中

        if (!system.io.directory.exists(server.mappath("~/filelist/files")))

            system.io.directory.createdirectory(server.mappath("~/filelist/files"));

 

        //儲存檔案

        fileupload.postedfile.saveas(server.mappath("~/filelist/files/" + fileupload.filename));

        scriptmanager.registerstartups教程cript(this.page, this.gettype(), "", "alert('上傳成功');", true);

    }

 


當然在上傳事件中會有一些邏輯判斷和異常捕獲,為了達到一目瞭然的效果,在這裡就把它們省掉了。

 

補充一句刪除檔案代碼:

//刪除伺服器上的檔案

system.io.file.delete(server.mappath("~/filelist/files/xxx.doc"));

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.