[ASP.NET WebForm] #7 檔案的上傳、下載、刪除

本篇重點:

  • FileUpload​
  • 事件程式碼

FileUpload​

在 ASP.NET 中,我們可以透過 FileUpload 控制項來上傳檔案,並且顯示在 GridView 的欄位中。<br/><br/>

STEP 1:在畫面中插入一個 Fileupload、上傳的 Button、顯示錯誤訊息的 Label。<br/>

螢幕擷取畫面 2023-07-14 091404

<div>
     <asp:FileUpload ID="FUPD" runat="server" /> <asp:Button ID="UploadBTN" runat="server" Text="上傳" /><br/>
     <asp:Label ID="ErrLB" runat="server" ForeColor="Red"></asp:Label>
</div>

STEP 2:前置作業布局。<br/> WEB 專案 (右鍵) –> 加入 –> 新資料夾 (File)。<br/>

螢幕擷取畫面 2023-07-13 155010

在 Web.config 設定上傳檔案的最大值。<br/>

 <system.web>下
    'x MB*1024
    <httpRuntime maxRequestLength="25600" />

事件程式碼

STEP 3: 在 Button 後端事件加上程式碼。

上傳檔案

'清空錯誤訊息
        ErrLB.Text = ""

        '判斷是否有選取檔案
        If FUPD.HasFile = False Then
            ErrLB.Text = "<錯誤>您未選擇檔案!"
        Else
            '判斷檔案類型
            If System.IO.Path.GetExtension(FUPD.FileName).ToLower() = ".pdf" Or System.IO.Path.GetExtension(FUPD.FileName).ToLower() = ".jpg" Then
                '上限大小數值計算:X MB*1024*1024
                If FUPD.PostedFile.ContentLength > 5242880 Then
                    ErrLB.Text = "<錯誤>您上傳的檔案大小限制為5MB以內!"
                End If
            Else
                ErrLB.Text = "<錯誤>您選擇的檔案類型錯誤!請上傳PDF檔或JPG檔。"
            End If
        End If

        If ErrLB.Text = "" Then
            FUPD.PostedFile.SaveAs(Server.MapPath("/File/123" & System.IO.Path.GetExtension(FUPD.FileName).ToLower()))
            '顯示成功訊息
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "alert", "alert('檔案上傳成功~');", True)
        End If

刪除檔案

My.Computer.FileSystem.DeleteFile(Server.MapPath("/File/123" & System.IO.Path.GetExtension(FUPD.FileName).ToLower()))

下載檔案

    If My.Computer.FileSystem.FileExists(Server.MapPath("/File/123.jpg")) = True Then
        Dim dwl As New System.Net.WebClient()
        dwl.DownloadFile(Server.MapPath("/File/123.jpg"), System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\test.jpg")
        dwl.Dispose()
        '顯示成功訊息
        ScriptManager.RegisterStartupScript(Me, Me.GetType(), "alert", "alert('檔案已經下載至您電腦的桌面');", True)
    Else
        '顯示錯誤訊息
        ScriptManager.RegisterStartupScript(Me, Me.GetType(), "alert", "alert('檔案不存在!');", True)
    End If

【補充】<br/> 選擇檔案屬性​:FileFLD.HasFile = True<br/> 取得副檔名​:System.IO.Path.GetExtension(FileFLD.FileName).ToLower()<br/> 檔案大小 XMB10241024​:FileFLD.PostedFile.ContentLength<br/> 檔案上傳:​FileFLD.PostedFile.SaveAs(Server.MapPath("~/File/xx.pdf"))<br/> 檔案命名 (​現在時間字串):Now.ToString(“yyyyMMddHHmmss”)<br/> 檔案刪除:​My.Computer.FileSystem.DeleteFile(Server.MapPath(“~/File/伺服器路徑.png"))​<br/>

檔案上傳:

Dim dwl As New System.Net.WebClient()​
dwl.DownloadFile(Server.MapPath(“~/File/伺服器路徑.png”), System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & “\桌面儲存路徑.png")​
dwl.Dispose()