[VB.NET] แจกโค้ดฟรีในการอัพโหลดไฟล์ขึ้นสู่โฮสติ้งด้วยการใช้ FTP
http://www.g2gnet.com/webboard/images/vbnet/ftpsample.pngสำหรับโค้ดชุดนี้ก็จะเป็นการอัพโหลดไฟล์ภาพขึ้นสู่โฮสติ้ง และให้ทำการแสดงผลจากลิ้งค์ที่รับมา โดยแอดมินเลือกใช้ฟรีโฮสติ้ง HelioHost.org ซึ่งให้บริการพื้นที่ขนาด 1 GB. และฐานข้อมูล MySQL ขนาด 1 GB. โดยไม่จำกัดจำนวนฐานข้อมูล ส่วนอื่นๆก็แทบจะไม่จำกัดการใช้งานใดๆเลย เข้าไปสมัครใช้งานกันน่ะครับ ซึ่งต่อไปแอดมินก็จะใช้โฮสตัวนี้ทำการทดสอบการเขียนโปรแกรมแบบออนไลน์ และทำการอัพโหลดภาพไปเก็บไว้ที่เดียวกัน ...
มาดูวิธีการตั้งค่า FTP Account ให้กับ Users ก่อน ...
เลือก FTP Accounts ...
http://www.g2gnet.com/webboard/images/vbnet/ftpaccount.png
กำหนดชื่อ รหัสผ่าน และตำแหน่งที่จะเก็บไฟล์ ... ขอให้สังเกต Directory ค่าที่จะถูกกำหนดดีฟอลท์มันจะอยู่ที่ public_html/g2gnet.heliohost.org/usertestแต่แอดมินจะตัดในส่วนสีแดงทิ้งออกไป เพื่อให้ง่ายต่อการหาตำแหน่ง เวลาที่เราไปเขียนโค้ดใน VB .NET ...
http://www.g2gnet.com/webboard/images/vbnet/ftpaccountadd.png
การตั้งค่าล็อคอินให้กับ Users ใน FTP Client ...
http://www.g2gnet.com/webboard/images/vbnet/ftpclient.png
ส่วนของ Root Directory ของ Users แอดมินเพิ่มโฟลเดอร์เข้าไปคือ upload ... ระวังตัวอักษรตัวเล็กตัวใหญ่ด้วยครับ เพราะนี่เป็น Linux Server มันมีผลต่อการเขียนโปรแกรม ...
http://www.g2gnet.com/webboard/images/vbnet/ftpclientlog.png
Add Reference Chilkat ... คลิ๊กเพื่อดาวน์โหลด Chilkat .Net Component ที่นี่ (เฉพาะสมาชิกเท่านั้น)
http://www.g2gnet.com/webboard/images/vbnet/ftpchilkat.png
มาดูโค้ดกันเถอะ ...
Imports System.IO
Imports System.Net
Imports Chilkat.Ftp2
Public Class frmFTPsample
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
'// ลิ้งค์ที่จะทำการแสดงผลภาพ หลังจากการอัพโหลด
Dim MyURL As String = "http://g2gnet.heliohost.org/usertest/upload/"
Private Sub frmFTPsample_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Call UnlockChilkat()
'// Initialized.
'// For FreeHostia.com
txtRemoteDir.Text = "/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 UploadFTP()
'// 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 UploadFTP()
Dim ftp As New Chilkat.Ftp2
ftp.Hostname = "ftp.g2gnet.heliohost.org"
ftp.Username = "USERNAME"
ftp.Password = "PASSWORD"
'/ Connect and login to the FTP server.
Dim success As Boolean = ftp.Connect()
If (success <> True) Then
MessageBox.Show(ftp.LastErrorText)
Exit Sub
End If
'/ Change to the remote directory where the file will be uploaded.
success = ftp.ChangeRemoteDir("upload/")
If (success <> True) Then
MessageBox.Show(ftp.LastErrorText)
Exit Sub
End If
'/ Upload a file such as "D:\123.jpg"
Dim localPath As String = UploadFileName
'// Upload to /thongkorn.com/upload/ชื่อ+นามสกุลไฟล์ภาพ
Dim remoteFilename As String = txtRemoteDir.Text.Trim & MyPictureName
success = ftp.PutFile(localPath, remoteFilename)
If (success <> True) Then
MessageBox.Show(ftp.LastErrorText)
Exit Sub
End If
success = ftp.Disconnect()
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("")
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 frmFTPsample_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) ได้ที่นี่ ...
ขอบคุณคับ Thankyou ขอบคุณครับ :) ขอบคุณครับ
หน้า:
[1]