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

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

[VB.NET] โค้ดการใช้ Line Messaging API ด้วยการส่งไฟล์รูปภาพไปเก็บไว้ที่ Cloudinary ก่อนส่งต่อไปที่ LINE

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

326

กระทู้

519

โพสต์

7025

เครดิต

ผู้ดูแลระบบ

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

Rank: 9Rank: 9Rank: 9

เครดิต
7025
โพสต์ 7 วันที่แล้ว | ดูโพสต์ทั้งหมด |โหมดอ่าน



*** จะต้องติดตั้ง CloudinaryDotNet เข้าไปใหม่ก่อนด้วย เพราะโค้ดต้นฉบับไม่ได้แนบไฟล์ DLL ไปด้วย ***
*** การติดตั้ง CloudinaryDotNet จะติดตั้ง NewTonSoft มาให้อัตโนมัติ ***

การใช้ Nuget เพื่อทำการติดตั้ง CloudinaryDotNet ... (เป็นที่เก็บไฟล์ Media ต่างๆ)

สมัครใช้งาน Cloudinary.com ได้ที่นี่ ...

คลิปวิดีโอในการสมัครใช้งาน Line Official Account เพื่อรับค่า Channel Access Token และ UserID (สำคัญ)

คลิปวิดีโอประกอบการอธิบายในโค้ดชุดนี้ ...

มาดูโค้ดฉบับเต็มกันเถอะ ... อย่าลืมใส่ค่าต่างๆก่อนที่จะรันโปรแกรมด้วย ...
  1. '// สมัครการใช้งาน Line Messaging API ที่
  2. '// https://manager.line.biz/
  3. '// https://developers.line.biz/en/
  4. '// จากนั้น สร้าง Channel ใน Line Messaging API
  5. '// รับ Channel Access Token และ User ID จากหน้า Line Console

  6. '// ติดตั้ง Library Newtonsoft.Json เพื่อช่วยจัดการ JSON
  7. '// ใน NuGet Package Manager Console ใช้คำสั่ง:
  8. '// Install-Package Newtonsoft.Json
  9. '// .Net Framework 4.5

  10. '// .Net SDK & Cloudinary Document
  11. '// https://cloudinary.com/documentation/dotnet_integration
  12. '// Sign Up
  13. '// https://www.cloudinary.com

  14. Imports System.IO
  15. Imports CloudinaryDotNet
  16. Imports CloudinaryDotNet.Actions
  17. Imports System.Net.Http
  18. Imports System.Net.Http.Headers
  19. Imports Newtonsoft.Json
  20. Imports System.Text

  21. Public Class frmLineAPICloudinary
  22.     '// ------------------------------------------------------------------------------------------------
  23.     '// เก็บตำแหน่งและชื่อไฟล์ภาพต้นฉบับที่ต้องการอัพโหลด
  24.     Dim PictureUploadPath As String = String.Empty
  25.     '// แยกชื่อไฟล์+นามสกุล ออกจากโฟลเดอร์
  26.     Dim UploadFileName As String = ""
  27.     '// Default path.
  28.     Dim PictureDefaultPath As String = MyPath(Application.StartupPath) & "Images"

  29.     '// Cloudinary Configuration
  30.     Private Const CLOUD_NAME As String = "CLOUD_NAME"
  31.     Private Const API_KEY As String = "API_KEY"
  32.     Private Const API_SECRET As String = "API_SECRET"
  33.     '// กำหนดโฟลเดอร์ที่เก็บไฟล์บน Cloudinary
  34.     Private Const CLOUD_FOLDER As String = "LineAPI"    '// สามารถเปลี่ยนชื่อโฟลเดอร์ได้ใหม่เลย

  35.     '// Line Bot Config
  36.     Private Const LINE_ACCESS_TOKEN As String = ""
  37.     Private Const USER_ID As String = ""
  38.     '// ------------------------------------------------------------------------------------------------

  39.     Private Sub frmLineAPICloudinary_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  40.         txtMessage.Text = "ทดสอบการทำงานของ Line Messaging API ด้วยการส่งข้อความและรูปภาพ"
  41.     End Sub

  42.     '// ------------------------------------------------------------------------------------------------
  43.     '// ส่งข้อความและรูปภาพไปยัง LINE
  44.     '// ------------------------------------------------------------------------------------------------
  45.     Private Sub btnSendMessage_Click(sender As Object, e As EventArgs) Handles btnSendMessage.Click
  46.         '// ตรวจสอบว่าทั้งข้อความและภาพว่างหรือไม่
  47.         If String.IsNullOrWhiteSpace(txtMessage.Text.Trim) AndAlso String.IsNullOrWhiteSpace(PictureUploadPath) Then
  48.             MessageBox.Show("กรุณาใส่ข้อความหรือเลือกภาพก่อนส่ง", "คำเตือน", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  49.             Return
  50.         Else
  51.             '// ทำการส่งข้อความและไฟล์ภาพไปใน Line Bot
  52.             Call UploadImageAndSendToLine(PictureUploadPath, txtMessage.Text)
  53.         End If
  54.         '// Clear
  55.         UploadFileName = ""
  56.         PictureUploadPath = String.Empty
  57.         picData.Image = Image.FromFile(PictureDefaultPath & "NoImage.gif")
  58.     End Sub

  59.     '// ------------------------------------------------------------------------------------------------
  60.     '// คำสั่ง Async ใช้เพื่อระบุว่าฟังก์ชันหรือเมธอดสามารถดำเนินการแบบ Asynchronous
  61.     '// หรือเป็นทำงานแบบไม่รอให้เสร็จสมบูรณ์ก่อนที่จะไปทำคำสั่งถัดไปได้
  62.     '// โดยปกติจะใช้ร่วมกับคำสั่ง Await เพื่อเรียกใช้งานที่ใช้เวลานาน
  63.     '// เช่น การร้องขอข้อมูลจาก API, อ่าน/เขียนไฟล์, หรือรอเครือข่าย โดยไม่บล็อกส่วนที่เหลือของแอพพลิเคชัน
  64.     '// ------------------------------------------------------------------------------------------------
  65.     Public Async Function UploadImageAndSendToLine(ByVal imagePath As String, ByVal message As String) As Task
  66.         Dim account = New Account(CLOUD_NAME, API_KEY, API_SECRET)
  67.         Dim cloudinary = New Cloudinary(account)
  68.         Dim uploadResult As ImageUploadResult = Nothing
  69.         Dim publicId As String = Nothing
  70.         Dim imageUrl As String = String.Empty
  71.         Try
  72.             '// 1. Upload Image to Cloudinary
  73.             If Not String.IsNullOrEmpty(imagePath) AndAlso IO.File.Exists(imagePath) Then
  74.                 Dim uploadParams = New ImageUploadParams() With {
  75.                     .File = New FileDescription(imagePath),
  76.                     .Folder = CLOUD_FOLDER '// Line API folder on Cloudinary.
  77.                 }
  78.                 uploadResult = cloudinary.Upload(uploadParams)
  79.                 imageUrl = uploadResult.SecureUrl.ToString()
  80.                 publicId = uploadResult.PublicId
  81.             End If

  82.             '// 2. Send to LINE Messaging API
  83.             Using client As New HttpClient()
  84.                 client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", LINE_ACCESS_TOKEN)
  85.                 '// เตรียมรายการข้อความ สร้าง Payload ตามรูปแบบที่ Line API ต้องการ
  86.                 '// Payload คือเนื้อหาข้อมูลที่ส่งไปยัง Line Server ผ่าน API เช่น การส่งข้อความ, การส่งรูปภาพ หรือการสร้าง Flex Message
  87.                 '// ประกาศตัวแปร messages เป็นแบบ List(Of Object) จากนั้นค่อยนำไปแปลงให้อยู่ในรูปแบบ JSON Format
  88.                 Dim messages = New List(Of Object)
  89.                 '// ตรวจสอบว่ามีข้อความ
  90.                 If Not String.IsNullOrEmpty(message) Then
  91.                     messages.Add(New With {.type = "text", .text = message})
  92.                 End If
  93.                 '// ตรวจสอบว่ามี URL รูปภาพ
  94.                 If Not String.IsNullOrEmpty(imageUrl) Then
  95.                     messages.Add(New With {
  96.                         .type = "image",
  97.                         .originalContentUrl = imageUrl,
  98.                         .previewImageUrl = imageUrl
  99.                     })
  100.                 End If
  101.                 Dim payload = New With {
  102.                     .to = USER_ID,
  103.                     .messages = messages.ToArray()
  104.                 }
  105.                 '// สำหรับวิดีโอ
  106.                 'If Not String.IsNullOrEmpty(videoUrl) AndAlso Not String.IsNullOrEmpty(videoPreviewUrl) Then
  107.                 'messages.Add(New With {
  108.                 'Key .type = "video",
  109.                 'Key .originalContentUrl = videoUrl,
  110.                 'Key .previewImageUrl = videoPreviewUrl
  111.                 '})
  112.                 'End If

  113.                 '// แปลงเป็น JSON แล้วส่ง
  114.                 Dim json = JsonConvert.SerializeObject(payload, Formatting.Indented)
  115.                 '// ตัวอย่าง:
  116.                 '// {
  117.                 '//  "to": "USER_ID",
  118.                 '//  "messages": [
  119.                 '//     {
  120.                 '//       "type": "text",
  121.                 '//       "text": "สวัสดีครับ! นี่คือข้อความจาก Line Messaging API"
  122.                 '//     },
  123.                 '//     {
  124.                 '//       "type": "image",
  125.                 '//       "originalContentUrl": "https://example.com/image.jpg",
  126.                 '//       "previewImageUrl": "https://example.com/image_preview.jpg" (หรือใช้ชื่อไฟล์ภาพ Content ตัวเดียวกันได้เลย)
  127.                 '//     }
  128.                 '//   ]
  129.                 '// }
  130.                 Dim content = New StringContent(json, Encoding.UTF8, "application/json")
  131.                 Dim response = Await client.PostAsync("https://api.line.me/v2/bot/message/push", content)
  132.                 Dim result = Await response.Content.ReadAsStringAsync()
  133.                 If Not response.IsSuccessStatusCode Then
  134.                     MessageBox.Show("เกิดข้อผิดพลาด: " & response.StatusCode & vbCrLf & result, "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  135.                 End If
  136.                 '// หากต้องการแสดงข้อความแจ้งเตือน
  137.                 'If response.IsSuccessStatusCode Then
  138.                 'MessageBox.Show("ส่งข้อความและรูปภาพสำเร็จ!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information)
  139.                 'Else
  140.                 'MessageBox.Show("เกิดข้อผิดพลาด: " & response.StatusCode & vbCrLf & responseBody, "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  141.                 'End If
  142.             End Using

  143.         Catch ex As Exception
  144.             MessageBox.Show("Error: " & ex.Message)

  145.             '// 3: Delete Image From Cloudinary.
  146.         Finally
  147.             If Not String.IsNullOrEmpty(publicId) Then
  148.                 Try
  149.                     Dim deletionParams As New DeletionParams(publicId)
  150.                     Dim deletionResult = Cloudinary.Destroy(deletionParams)
  151.                     'If deletionResult.Result = "ok" Then
  152.                     '    MessageBox.Show("ลบภาพจาก Cloudinary สำเร็จ", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  153.                     'Else
  154.                     '    MessageBox.Show("ลบภาพไม่สำเร็จ: " & deletionResult.Result, "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  155.                     'End If
  156.                 Catch ex1 As Exception
  157.                     MessageBox.Show("ลบภาพไม่สำเร็จ: " & ex1.Message, "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  158.                 End Try
  159.             End If
  160.         End Try
  161.     End Function

  162.     '// ------------------------------------------------------------------------------------------------
  163.     '// เบราซ์หาไฟล์ภาพ
  164.     '// ------------------------------------------------------------------------------------------------
  165.     Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
  166.         Dim dlgImage As OpenFileDialog = New OpenFileDialog()
  167.         '// Open File Dialog
  168.         With dlgImage
  169.             .InitialDirectory = PictureDefaultPath
  170.             .Title = "Select Image File"
  171.             .Filter = "Format (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png"
  172.             .FilterIndex = 1
  173.             .RestoreDirectory = True
  174.         End With
  175.         '// Select OK after Browse ...
  176.         If dlgImage.ShowDialog() = DialogResult.OK Then
  177.             '// ตรวจสอบก่อนว่าขนาดไฟล์เกิน 1 MB. หรือไม่ (Cloudinary น่าจะอัพโหลดได้สูงสุด 10 MB.)
  178.             Dim info As New FileInfo(dlgImage.FileName)
  179.             If (info.Length / 1024) > 1024 Then
  180.                 MessageBox.Show("The image file you selected is of size " & Format((info.Length / 1024), "#,##0") & " KB. is too big more than 1,024 KB.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  181.                 Exit Sub
  182.             End If
  183.             '// Put the current image file into PictureBox Control.
  184.             picData.Image = Image.FromFile(dlgImage.FileName)
  185.             '// เอาเฉพาะชื่อไฟล์และนามสกุลภาพ (Filename + Extension) เช่น thongkorn.png
  186.             UploadFileName = dlgImage.SafeFileName
  187.             '// เอาไฟล์ภาพมาเต็มพาธ เพื่อระบุต้นทางไฟล์ก่อนทำการอัพโหลด
  188.             PictureUploadPath = dlgImage.FileName
  189.         End If
  190.     End Sub

  191.     '// ------------------------------------------------------------------------------------------------
  192.     Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
  193.         picData.Image = Image.FromFile(PictureDefaultPath & "NoImage.gif")
  194.         UploadFileName = ""
  195.         PictureUploadPath = String.Empty
  196.     End Sub

  197.     Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
  198.         Me.Close()
  199.     End Sub

  200.     Private Sub frmLineAPICloudinary_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
  201.         Me.Dispose()
  202.         GC.SuppressFinalize(Me)
  203.         Application.Exit()
  204.     End Sub

  205. #Region "FUNCTION"
  206.     '// / --------------------------------------------------------------------------------
  207.     '// / Get my project path
  208.     '// / AppPath = C:\My Project\bin\debug
  209.     '// / Replace "\bin\debug" with ""
  210.     '// / Return : C:\My Project\
  211.     Function MyPath(ByVal AppPath As String) As String
  212.         '/ MessageBox.Show(AppPath);
  213.         AppPath = AppPath.ToLower()
  214.         '/ Return Value
  215.         MyPath = AppPath.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "")
  216.         '// If not found folder then put the \ (BackSlash) at the end.
  217.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  218.     End Function
  219. #End Region

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

ดาวน์โหลดโค้ดต้นฉบับ VB.NET & .Net Framework 4.5.2+ ได้ที่นี่ ...

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

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

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

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

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

GMT+7, 2025-5-12 08:09 , Processed in 0.054475 second(s), 5 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

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