Ahmad Masykur

Share your knowledge although one function!

About the author

Ahmad Masykur is a Software Architecture Engineer at PT. Freeport Indonesia Jakarta Indonesia.
In this blog, I share things of interest to me. Most topics are likely to be related to software development, but don't hold me to it.

Certificates



Awards


Powered by

Prayer Time

July 30, 2010
الفجر/Dawn 04:43:13
الشروق/Sunrise 06:03:59
الظهر/Noon 11:59:21
العصر/Afternoon 15:21:26
المغرب/Sunset 17:54:43
العشاء/Dusk 19:07:02
Jakarta  Indonesia
Prayer time widget created by
Ahmad Masykur

Page List

Validators


Ahmad Masykur

Upload dan Download File

Upload file di ASP.NET dapat menggunakan ASP.NET Web Control FileUpload. Untuk implementasi upload tinggal pasang control FileUpload dan satu Button.

<asp:FileUpload ID="fileUpload" runat="server" Width="300" />
<asp:Button id="btnUpload" runat="server" Text="Upload" />

Pada codebehind, buat handler untuk btnUpload.Click

Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpdate.Click
    Try
        Dim objFile As FileInfo = New FileInfo

        If fileUpload.PostedFile Is Nothing Then
            Exit Sub
        End If
        If Not fileUpload.HasFile Then
            Exit Sub
        End If

        Dim path As String = Me.MapPath("files/")
        path = path.Replace("/", "\")
        If Not Directory.Exists(path) Then
            Directory.CreateDirectory(path)
        End If
        fileUpload.SaveAs(path + fileUpload.PostedFile.FileName)

    Catch exc As Exception    
        'Exception code here
    End Try
End Sub

Untuk download file, kita bisa menggunakan Response untuk mengirimkan data ke client. Misalkan ada sebuat tombol untuk download, handler tombol tersebut dapat ditulis sebagai berikut.

Dim path As String = Me.MapPath("files/")
path = path.Replace("/", "\")
Dim namafile As String = "namafile.ext"
Response.Clear()    'Bersihkan buffer stream
'Tambahkan header namafile
Response.AppendHeader("content-disposition", "attachment; filename=" + namafile)
Response.WriteFile(path + namafile)
Response.End()
Response.Close()

Jika file yang diupload perlu diolah terlebih dahulu atau disimpan dalam database, maka file tersebut dapat dibaca menggunakan BinaryReader. Berikut contoh sederhana untuk melakukan enkripsi sebelum file disimpan di filesystem atau database.

Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpdate.Click
    Try
        Dim objFile As FileInfo = New FileInfo

        If fileUpload.PostedFile Is Nothing Then
            Exit Sub
        End If
        If Not fileUpload.HasFile Then
            Exit Sub
        End If

        Dim path As String = Me.MapPath("files/")
        path = path.Replace("/", "\")
        If Not Directory.Exists(path) Then
            Directory.CreateDirectory(path)
        End If
        Dim uploadedStream As New BinaryReader(fileUpload.PostedFile.InputStream)
	  Dim bytesStream As Byte() = uploadedStream.ReadBytes(fileUpload.PostedFile.ContentLength)
        'Tutup stream
        uploadedStream.Close()
        'Panggil fungsi enkripsi (contoh)
        Dim cipherStream As Byte() = Encrypt(bytesStream)
        'Simpan hasil enkripsi dalam filesystem
        Using _fileStream As New FileStream(path + fileUpload.FileName, FileMode.Create, FileAccess.Write)
            _fileStream.Write(cipherStream, 0, cipherStream.Length)
            _fileStream.Flush()
            _fileStream.Close()
        End Using
    Catch exc As Exception    
        'Exception code here
    End Try
End Sub

Jika file telah dienkripsi, maka pada waktu download file tersebut juga harus didekripsi sebelum dikirimkan ke client.

path = path.Replace("/", "\") 
Dim namafile As String = "namafile.ext" 
'Buka stream
Dim _fileStream As New FileStream(path + namafile, FileMode.Open, FileAccess.Read)
Dim _binReader As New BinaryReader(_fileStream)
Dim _cipherStream As Byte() = _binReader.ReadBytes(_fileStream.Length)
_binReader.Close()
_fileStream.Close()
'Panggil fungsi dekripsi (contoh)
Dim _plainStream As Byte() = Decrypt(_cipherStream)
'Kirim stream ke client
Response.Clear() 'Bersihkan buffer stream 
'Tambahkan header namafile 
Response.AppendHeader("content-disposition", "attachment; filename=" + namafile) 
Response.BinaryWrite(plainStream)
Response.Flush()
Response.End() 
Response.Close()

Semoga bermanfaat


Categories: ASP.NET
Permalink | Comments (9) | Post RSSRSS comment feed

Comments

sandy kwary Singapore | Reply

Friday, September 21, 2007 9:46 AM

sandy kwary

Hi, i need to ask a question, why i get internet explorer error "Action Cancelled"

dewi Indonesia | Reply

Tuesday, October 30, 2007 10:06 AM

dewi

mas, itu using nya pake using apa ya ? kok ga dicantumkan ?
karena saya menggunakan bahasa C# apakah ada perbedaan yang mendasar ?
thank u

busby seo challenge United States | Reply

Tuesday, August 26, 2008 11:26 AM

busby seo challenge

great i love to collect code... thanks http://pinayspeak.com | http://alaminos.net

Rab apartments United States | Reply

Thursday, December 04, 2008 2:13 PM

Rab apartments

thanks for sharing such an valuable code..
regards,
jhon

bugatti veyron Norway | Reply

Thursday, December 11, 2008 3:33 PM

bugatti veyron

Hi, i need to ask a question, why i get internet explorer error "Action Cancelled"

Pankaj United States | Reply

Friday, December 26, 2008 3:30 AM

Pankaj

Nice code!!! Thanks for sharing with us

Cayenne Pepper Diet United States | Reply

Wednesday, January 07, 2009 2:59 AM

Cayenne Pepper Diet

thanks for sharing such an valuable code..
regards,
Peter

Google’s WebSpam Team 2009 Using FireFox Plugin United States | Reply

Thursday, January 15, 2009 11:07 AM

Google’s WebSpam Team 2009 Using FireFox Plugin

really?thanks for the info and update me for the next post.

Birch Tire and Auto Service United Kingdom | Reply

Tuesday, February 10, 2009 2:55 AM

Birch Tire and Auto Service

You are requesting Dan Duke - varaamendoeira.wma (5.0 MB) ... Premium Membership allows you to download files without any limits, timers etc ...

http://www.birchtireautoservice.com/
Birch Tire has provided 3 generations of automobile service at our location on Route 46 in Rockaway, NJ.

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading