[VB.NET] การอัพโหลดไฟล์ขึ้นสู่โฮสติ้งด้วยการใช้โปรโตคอล SFTP
http://www.g2gnet.com/webboard/images/vbnet/sftp.pngจากตอนที่แล้วเราได้ อัพโหลดไฟล์ด้วยการใช้โปรโตคอล FTP คราวนี้ลองมาใช้ SFTP กันดูบ้าง ... SFTP หรือ Secure File Transfer Protocol เป็นโปรแกรมที่ใช้ในการส่งถ่ายข้อมูลไฟล์เอกสาร โดยลักษณะเด่นของ SFTP คือ การทำงานบน SSH ซึ่งมีการเข้ารหัสข้อมูล ทำให้การส่งย้ายไฟล์มีความปลอดภัยมากยิ่งขึ้นเมื่อเทียบกับ FTP ธรรมดา ... สมัครใช้งานฟรีโฮสติ้ง HelioHost.org ได้ที่ ...
ต้อง Add Reference เข้ามาด้วยล่ะครับ ... ดาวน์โหลด Chilkat .Net Component ได้ที่นี่ (สำหรับสมาชิกเท่านั้น) http://www.g2gnet.com/webboard/images/vbnet/FTPChilkat.png
สำหรับการเข้าสู่ระบบผ่าน FTP Client ไปยัง HelioHost.org ...
http://www.g2gnet.com/webboard/images/vbnet/sftpclient.png
มาดูโค้ดกันเถอะ ...
Imports System.IO
Imports System.Net
Imports Chilkat.Ftp2
Public Class frmUploadImageSFTP
Dim UploadFileName As String = ""'// Full Path and File name of Image.
Dim streamPic As Stream '// Use Steam instead IO.
Dim PicturePath As String = MyPath(Application.StartupPath) & "Images\"
'// แยกชื่อไฟล์+นามสกุล เพื่อทำการ Upload ไปยัง Hosting
Dim MyPictureName As String = String.Empty
'// ลิ้งค์ที่จะทำการแสดงผลภาพ หลังจากการอัพโหลด (สร้างโฟลเดอร์ upload เพิ่มขึ้นด้วยครับ)
Dim MyURL As String = "http://g2gnet.heliohost.org/upload/"
Private Sub frmUploadImageSFTP_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Call UnlockChilkat()
'// Initialized.
'// For HelioHost.org
txtRemoteDir.Text = "/home/g2gnet/public_html/upload/"
Label1.Text = ""
picData.Image = Image.FromFile(PicturePath + "NoImage.gif")
Label3.Text = MyURL
End Sub
Private Sub btnBrowse_Click(sender As System.Object, e As System.EventArgs) Handles btnBrowse.Click
Dim dlgImage As OpenFileDialog = New OpenFileDialog()
' / Open File Dialog
With dlgImage
'.InitialDirectory = PicturePath 'PicturePath
.Title = "เลือกภาพ"
.Filter = "รูปแบบภาพ (*.jpg;*.png;*.gif;*.bmp)|*.jpg;*.png;*.gif;*.bmp"
.FilterIndex = 1
.RestoreDirectory = True
End With
' Select OK after Browse ...
If dlgImage.ShowDialog() = DialogResult.OK Then
'// New Image
UploadFileName = dlgImage.FileName
' Get file size
Dim info As New FileInfo(dlgImage.FileName)
If (info.Length / 1024) > 1024 Then
MessageBox.Show("ไฟล์ภาพที่คุณเลือกมีขนาด " & Format((info.Length / 1024), "#,##0") & " KB. ซึ่งมีขนาดใหญ่เกินกว่า 1,024 KB.", "รายงานสถานะ", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Exit Sub
End If
Dim arr() As String = Split(dlgImage.FileName, "\")
'// ตัดเอาเฉพาะชื่อไฟล์ เช่น sample.png เพื่อส่งค่าไปต่อ RemoteDir
MyPictureName = arr(UBound(arr))
'/
picData.Image = Image.FromFile(UploadFileName)
Label1.Text = UploadFileName
End If
End Sub
' / -----------------------------------------------------------------------------
' / Use Steam instead IO.
' / -----------------------------------------------------------------------------
Sub ShowPicture(PicName As String)
Dim imgDB As Image
' Get the name of the image file from the database.
If PicName.ToString <> "" Then
' Verify that the image file meets the specified location.
If System.IO.File.Exists(PicturePath & PicName.ToString) Then
' Because when deleting the image file is locked, it can not be removed.
' The file is closed after the image is loaded, so you can delete the file if you need to
streamPic = File.OpenRead(PicturePath & PicName.ToString)
imgDB = Image.FromStream(streamPic)
picData.Image = imgDB
UploadFileName = PicName
Else
' No images were retrieved from the database.
streamPic = File.OpenRead(PicturePath & "NoImage.gif")
imgDB = Image.FromStream(streamPic)
picData.Image = imgDB
UploadFileName = ""
End If
' Is null
Else
streamPic = File.OpenRead(PicturePath & "NoImage.gif")
imgDB = Image.FromStream(streamPic)
picData.Image = imgDB
UploadFileName = ""
End If
'//
streamPic.Dispose()
End Sub
Private Sub btnDeleteImg_Click(sender As System.Object, e As System.EventArgs) Handles btnDeleteImg.Click
picData.Image = Image.FromFile(PicturePath & "NoImage.gif")
UploadFileName = ""
Label1.Text = ""
End Sub
Private Sub btnUpload_Click(sender As System.Object, e As System.EventArgs) Handles btnUpload.Click
If picData.Image Is Nothing Or UploadFileName Is Nothing Or UploadFileName.Length = 0 Or UploadFileName = "" Then
MessageBox.Show("Please select the image file first.", "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
'//
Me.Cursor = Cursors.WaitCursor
'// Upload to Hosting with SFTP.
Call UploadSFTP()
'// Show Image From URL.
Call ShowImgURL(MyPictureName, picURL)
Me.Cursor = Cursors.Default
'// Clear
UploadFileName = ""
picData.Image = Image.FromFile(PicturePath + "NoImage.gif")
Label1.Text = ""
End Sub
Private Sub UploadSFTP()
Dim sftp As New Chilkat.SFtp
'/ Set some timeouts, in milliseconds: 1 Sec = 1,000 ms.
sftp.ConnectTimeoutMs = 15000
sftp.IdleTimeoutMs = 15000
'/ Connect to the SSH server.
'/ The standard SSH port = 22
'/ The hostname may be a hostname or IP address.
Dim hostname As String = "johnny.heliohost.org"
Dim port As Integer = 1373
Dim success As Boolean = sftp.Connect(hostname, port)
If (success <> True) Then
MessageBox.Show(sftp.LastErrorText)
Exit Sub
End If
'/ Authenticate with the SSH server.Chilkat SFTP supports
'/ both password-based authenication as well as public-key
'/ authentication.This example uses password authenication.
Dim Username As String = "SUPERUSER"
Dim Password As String = "PASSWORD"
success = sftp.AuthenticatePw(Username, Password)
If (success <> True) Then
MessageBox.Show(sftp.LastErrorText)
Exit Sub
End If
'/ After authenticating, the SFTP subsystem must be initialized:
success = sftp.InitializeSftp()
If (success <> True) Then
MessageBox.Show(sftp.LastErrorText)
Exit Sub
End If
'/ Upload from the local file to the SSH server.
'/ Important -- the remote filepath is the 1st argument,
'/ the local filepath is the 2nd argument;
Dim remoteFilePath As String = txtRemoteDir.Text + MyPictureName ' "/home/g2gnet/public_html/upload/" + MyPictureName
Dim localFilePath As String = UploadFileName
success = sftp.UploadFileByName(remoteFilePath, localFilePath)
If (success <> True) Then
MessageBox.Show(sftp.LastErrorText)
Exit Sub
End If
MessageBox.Show("File Uploaded Complete.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
'// Show Image From URL.
Public Sub ShowImgURL(PicName As String, ByRef picData As PictureBox)
'// Check
If Not IsValid(MyURL & PicName) Or PicName = "" Then
PicName = "NoImage.gif"
End If
Dim wClient As WebClient = New WebClient
Dim bmpImage As Bitmap = Bitmap.FromStream(New MemoryStream(wClient.DownloadData(MyURL & PicName + "?r=" + DateTime.Now.Ticks.ToString)))
Try
With picData
.SizeMode = PictureBoxSizeMode.StretchImage
.WaitOnLoad = True ' False
picData.Image = bmpImage
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
'// Check Valid Image.
Public Function IsValid(ByVal Url As String) As Boolean
Dim sStream As Stream
Dim URLReq As HttpWebRequest
Dim URLRes As HttpWebResponse
Try
URLReq = WebRequest.Create(Url + "?r=" + DateTime.Now.Ticks.ToString)
URLRes = URLReq.GetResponse()
sStream = URLRes.GetResponseStream()
Dim reader As String = New StreamReader(sStream).ReadToEnd()
Return True
Catch ex As Exception
'Url not valid
Return False
End Try
End Function
Public Sub UnlockChilkat()
Dim glob As New Chilkat.Global
Dim success As Boolean = glob.UnlockBundle("LOCK_KEY")
If (success <> True) Then
MessageBox.Show(glob.LastErrorText)
Exit Sub
End If
Dim status As Integer = glob.UnlockStatus
If (status = 2) Then
'MessageBox.Show("Unlocked using purchased unlock code.")
Else
MessageBox.Show("Unlocked in trial mode.")
End If
End Sub
' / Get my project path
' / AppPath = C:\My Project\bin\debug
' / Replace "\bin\debug" with "\"
' / Return : C:\My Project\
Function MyPath(ByVal AppPath As String) As String
'/ MessageBox.Show(AppPath);
AppPath = AppPath.ToLower()
'/ Return Value
MyPath = AppPath.Replace("\bin\debug", "\").Replace("\bin\release", "\").Replace("\bin\x86\debug", "\").Replace("\bin\x86\release", "\")
'// If not found folder then put the \ (BackSlash) at the end.
If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
End Function
Private Sub frmUploadImageSFTP_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
Me.Dispose()
GC.SuppressFinalize(Me)
Application.Exit()
End Sub
End Class
ดาวน์โหลดโค้ดต้นฉบับแบบเต็ม VB.NET (2010) ได้ที่นี่ ...
ขอบคุณครับ
หน้า:
[1]