ชุมชนคนรักภาษาเบสิค - Visual Basic Community

 ลืมรหัสผ่าน
 ลงทะเบียน
ค้นหา
ดู: 2751|ตอบกลับ: 1

[VB.NET] การอัพโหลดไฟล์ขึ้นสู่โฮสติ้งด้วยการใช้โปรโตคอล SFTP

[คัดลอกลิงก์]

311

กระทู้

502

โพสต์

6050

เครดิต

ผู้ดูแลระบบ

ทองก้อน ทับทิมกรอบ

Rank: 9Rank: 9Rank: 9

เครดิต
6050



จากตอนที่แล้วเราได้ อัพโหลดไฟล์ด้วยการใช้โปรโตคอล FTP คราวนี้ลองมาใช้ SFTP กันดูบ้าง ... SFTP หรือ Secure File Transfer Protocol เป็นโปรแกรมที่ใช้ในการส่งถ่ายข้อมูลไฟล์เอกสาร โดยลักษณะเด่นของ SFTP คือ การทำงานบน SSH ซึ่งมีการเข้ารหัสข้อมูล ทำให้การส่งย้ายไฟล์มีความปลอดภัยมากยิ่งขึ้นเมื่อเทียบกับ FTP ธรรมดา ... สมัครใช้งานฟรีโฮสติ้ง HelioHost.org ได้ที่ ...

ต้อง Add Reference เข้ามาด้วยล่ะครับ ...
ดาวน์โหลด Chilkat .Net Component ได้ที่นี่ (สำหรับสมาชิกเท่านั้น)

สำหรับการเข้าสู่ระบบผ่าน FTP Client ไปยัง HelioHost.org ...


มาดูโค้ดกันเถอะ ...
  1. Imports System.IO
  2. Imports System.Net
  3. Imports Chilkat.Ftp2

  4. Public Class frmUploadImageSFTP
  5.     Dim UploadFileName As String = ""  '// Full Path and File name of Image.
  6.     Dim streamPic As Stream     '// Use Steam instead IO.
  7.     Dim PicturePath As String = MyPath(Application.StartupPath) & "Images"
  8.     '// แยกชื่อไฟล์+นามสกุล เพื่อทำการ Upload ไปยัง Hosting
  9.     Dim MyPictureName As String = String.Empty
  10.     '// ลิ้งค์ที่จะทำการแสดงผลภาพ หลังจากการอัพโหลด (สร้างโฟลเดอร์ upload เพิ่มขึ้นด้วยครับ)
  11.     Dim MyURL As String = "http://g2gnet.heliohost.org/upload/"

  12.     Private Sub frmUploadImageSFTP_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  13.         Call UnlockChilkat()
  14.         '// Initialized.
  15.         '// For HelioHost.org
  16.         txtRemoteDir.Text = "/home/g2gnet/public_html/upload/"
  17.         Label1.Text = ""
  18.         picData.Image = Image.FromFile(PicturePath + "NoImage.gif")
  19.         Label3.Text = MyURL
  20.     End Sub

  21.     Private Sub btnBrowse_Click(sender As System.Object, e As System.EventArgs) Handles btnBrowse.Click
  22.         Dim dlgImage As OpenFileDialog = New OpenFileDialog()
  23.         ' / Open File Dialog
  24.         With dlgImage
  25.             '.InitialDirectory = PicturePath 'PicturePath
  26.             .Title = "เลือกภาพ"
  27.             .Filter = "รูปแบบภาพ (*.jpg;*.png;*.gif;*.bmp)|*.jpg;*.png;*.gif;*.bmp"
  28.             .FilterIndex = 1
  29.             .RestoreDirectory = True
  30.         End With
  31.         ' Select OK after Browse ...
  32.         If dlgImage.ShowDialog() = DialogResult.OK Then
  33.             '// New Image
  34.             UploadFileName = dlgImage.FileName
  35.             ' Get file size
  36.             Dim info As New FileInfo(dlgImage.FileName)
  37.             If (info.Length / 1024) > 1024 Then
  38.                 MessageBox.Show("ไฟล์ภาพที่คุณเลือกมีขนาด " & Format((info.Length / 1024), "#,##0") & " KB. ซึ่งมีขนาดใหญ่เกินกว่า 1,024 KB.", "รายงานสถานะ", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  39.                 Exit Sub
  40.             End If
  41.             Dim arr() As String = Split(dlgImage.FileName, "")
  42.             '// ตัดเอาเฉพาะชื่อไฟล์ เช่น sample.png เพื่อส่งค่าไปต่อ RemoteDir
  43.             MyPictureName = arr(UBound(arr))
  44.             '/
  45.             picData.Image = Image.FromFile(UploadFileName)
  46.             Label1.Text = UploadFileName
  47.         End If
  48.     End Sub

  49.     ' / -----------------------------------------------------------------------------
  50.     ' / Use Steam instead IO.
  51.     ' / -----------------------------------------------------------------------------
  52.     Sub ShowPicture(PicName As String)
  53.         Dim imgDB As Image
  54.         ' Get the name of the image file from the database.
  55.         If PicName.ToString <> "" Then
  56.             ' Verify that the image file meets the specified location.
  57.             If System.IO.File.Exists(PicturePath & PicName.ToString) Then
  58.                 ' Because when deleting the image file is locked, it can not be removed.
  59.                 ' The file is closed after the image is loaded, so you can delete the file if you need to
  60.                 streamPic = File.OpenRead(PicturePath & PicName.ToString)
  61.                 imgDB = Image.FromStream(streamPic)
  62.                 picData.Image = imgDB
  63.                 UploadFileName = PicName
  64.             Else
  65.                 ' No images were retrieved from the database.
  66.                 streamPic = File.OpenRead(PicturePath & "NoImage.gif")
  67.                 imgDB = Image.FromStream(streamPic)
  68.                 picData.Image = imgDB
  69.                 UploadFileName = ""
  70.             End If
  71.             ' Is null
  72.         Else
  73.             streamPic = File.OpenRead(PicturePath & "NoImage.gif")
  74.             imgDB = Image.FromStream(streamPic)
  75.             picData.Image = imgDB
  76.             UploadFileName = ""
  77.         End If
  78.         '//
  79.         streamPic.Dispose()
  80.     End Sub

  81.     Private Sub btnDeleteImg_Click(sender As System.Object, e As System.EventArgs) Handles btnDeleteImg.Click
  82.         picData.Image = Image.FromFile(PicturePath & "NoImage.gif")
  83.         UploadFileName = ""
  84.         Label1.Text = ""
  85.     End Sub

  86.     Private Sub btnUpload_Click(sender As System.Object, e As System.EventArgs) Handles btnUpload.Click
  87.         If picData.Image Is Nothing Or UploadFileName Is Nothing Or UploadFileName.Length = 0 Or UploadFileName = "" Then
  88.             MessageBox.Show("Please select the image file first.", "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  89.             Return
  90.         End If
  91.         '//
  92.         Me.Cursor = Cursors.WaitCursor
  93.         '// Upload to Hosting with SFTP.
  94.         Call UploadSFTP()
  95.         '// Show Image From URL.
  96.         Call ShowImgURL(MyPictureName, picURL)
  97.         Me.Cursor = Cursors.Default
  98.         '// Clear
  99.         UploadFileName = ""
  100.         picData.Image = Image.FromFile(PicturePath + "NoImage.gif")
  101.         Label1.Text = ""
  102.     End Sub

  103.     Private Sub UploadSFTP()
  104.         Dim sftp As New Chilkat.SFtp
  105.         '/ Set some timeouts, in milliseconds: 1 Sec = 1,000 ms.
  106.         sftp.ConnectTimeoutMs = 15000
  107.         sftp.IdleTimeoutMs = 15000
  108.         '/ Connect to the SSH server.  
  109.         '/ The standard SSH port = 22
  110.         '/ The hostname may be a hostname or IP address.
  111.         Dim hostname As String = "johnny.heliohost.org"
  112.         Dim port As Integer = 1373
  113.         Dim success As Boolean = sftp.Connect(hostname, port)
  114.         If (success <> True) Then
  115.             MessageBox.Show(sftp.LastErrorText)
  116.             Exit Sub
  117.         End If
  118.         '/ Authenticate with the SSH server.  Chilkat SFTP supports
  119.         '/ both password-based authenication as well as public-key
  120.         '/ authentication.  This example uses password authenication.
  121.         Dim Username As String = "SUPERUSER"
  122.         Dim Password As String = "PASSWORD"
  123.         success = sftp.AuthenticatePw(Username, Password)
  124.         If (success <> True) Then
  125.             MessageBox.Show(sftp.LastErrorText)
  126.             Exit Sub
  127.         End If
  128.         '/ After authenticating, the SFTP subsystem must be initialized:
  129.         success = sftp.InitializeSftp()
  130.         If (success <> True) Then
  131.             MessageBox.Show(sftp.LastErrorText)
  132.             Exit Sub
  133.         End If
  134.         '/ Upload from the local file to the SSH server.
  135.         '/ Important -- the remote filepath is the 1st argument,
  136.         '/ the local filepath is the 2nd argument;
  137.         Dim remoteFilePath As String = txtRemoteDir.Text + MyPictureName ' "/home/g2gnet/public_html/upload/" + MyPictureName
  138.         Dim localFilePath As String = UploadFileName
  139.         success = sftp.UploadFileByName(remoteFilePath, localFilePath)
  140.         If (success <> True) Then
  141.             MessageBox.Show(sftp.LastErrorText)
  142.             Exit Sub
  143.         End If
  144.         MessageBox.Show("File Uploaded Complete.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  145.     End Sub

  146.     '// Show Image From URL.
  147.     Public Sub ShowImgURL(PicName As String, ByRef picData As PictureBox)
  148.         '// Check
  149.         If Not IsValid(MyURL & PicName) Or PicName = "" Then
  150.             PicName = "NoImage.gif"
  151.         End If
  152.         Dim wClient As WebClient = New WebClient
  153.         Dim bmpImage As Bitmap = Bitmap.FromStream(New MemoryStream(wClient.DownloadData(MyURL & PicName + "?r=" + DateTime.Now.Ticks.ToString)))
  154.         Try
  155.             With picData
  156.                 .SizeMode = PictureBoxSizeMode.StretchImage
  157.                 .WaitOnLoad = True ' False
  158.                 picData.Image = bmpImage
  159.             End With
  160.         Catch ex As Exception
  161.             MessageBox.Show(ex.Message)
  162.         End Try
  163.     End Sub

  164.     '// Check Valid Image.
  165.     Public Function IsValid(ByVal Url As String) As Boolean
  166.         Dim sStream As Stream
  167.         Dim URLReq As HttpWebRequest
  168.         Dim URLRes As HttpWebResponse
  169.         Try
  170.             URLReq = WebRequest.Create(Url + "?r=" + DateTime.Now.Ticks.ToString)
  171.             URLRes = URLReq.GetResponse()
  172.             sStream = URLRes.GetResponseStream()
  173.             Dim reader As String = New StreamReader(sStream).ReadToEnd()
  174.             Return True
  175.         Catch ex As Exception
  176.             'Url not valid
  177.             Return False
  178.         End Try
  179.     End Function

  180.     Public Sub UnlockChilkat()
  181.         Dim glob As New Chilkat.Global
  182.         Dim success As Boolean = glob.UnlockBundle("LOCK_KEY")
  183.         If (success <> True) Then
  184.             MessageBox.Show(glob.LastErrorText)
  185.             Exit Sub
  186.         End If
  187.         Dim status As Integer = glob.UnlockStatus
  188.         If (status = 2) Then
  189.             'MessageBox.Show("Unlocked using purchased unlock code.")
  190.         Else
  191.             MessageBox.Show("Unlocked in trial mode.")
  192.         End If
  193.     End Sub

  194.     ' / Get my project path
  195.     ' / AppPath = C:\My Project\bin\debug
  196.     ' / Replace "\bin\debug" with ""
  197.     ' / Return : C:\My Project\
  198.     Function MyPath(ByVal AppPath As String) As String
  199.         '/ MessageBox.Show(AppPath);
  200.         AppPath = AppPath.ToLower()
  201.         '/ Return Value
  202.         MyPath = AppPath.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "").Replace("\bin\x86\release", "")
  203.         '// If not found folder then put the \ (BackSlash) at the end.
  204.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  205.     End Function

  206.     Private Sub frmUploadImageSFTP_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  207.         Me.Dispose()
  208.         GC.SuppressFinalize(Me)
  209.         Application.Exit()
  210.     End Sub

  211. End Class
คัดลอกไปที่คลิปบอร์ด

ดาวน์โหลดโค้ดต้นฉบับแบบเต็ม VB.NET (2010) ได้ที่นี่ ...

ขออภัย! โพสต์นี้มีไฟล์แนบหรือรูปภาพที่ไม่ได้รับอนุญาตให้คุณเข้าถึง

คุณจำเป็นต้อง ลงชื่อเข้าใช้ เพื่อดาวน์โหลดหรือดูไฟล์แนบนี้ คุณยังไม่มีบัญชีใช่ไหม? ลงทะเบียน

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด

0

กระทู้

58

โพสต์

10

เครดิต

Member

Rank: 2

เครดิต
10
โพสต์ 2022-10-25 15:12:50 | ดูโพสต์ทั้งหมด

ขอบคุณครับ
ขออภัย! คุณไม่ได้รับสิทธิ์ในการดำเนินการในส่วนนี้ กรุณาเลือกอย่างใดอย่างหนึ่ง ลงชื่อเข้าใช้ | ลงทะเบียน

รายละเอียดเครดิต

ข้อความล้วน|อุปกรณ์พกพา|ประวัติการแบน|G2GNet.com  

GMT+7, 2024-4-25 13:11 , Processed in 0.341036 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

ตอบกระทู้ ขึ้นไปด้านบน ไปที่หน้ารายการกระทู้