ส่งไฟล์ระหว่าง Service ต่าง ๆ ด้วย Base64 Encoding

Chiwa Kantawong (Pea)
2 min readMay 9, 2019

--

บางครั้งเราต้องการส่งไฟล์ต่างๆ ข้ามไปมาระหว่าง Service ต่างๆ ซึ่งก็มีวิธีการต่างๆ ได้มากมาย สำหรับตัวอย่างนี้ที่ผมใช้งานจริงเป็นการส่งไฟล์รูปภาพ จาก Service หนึ่งไปยังอีก Service หนึ่งโดยผ่าน Message Broker ซึ่งผมจะใช้วิธีการแปลงจากรูปภาพเป็น byte[] แล้วก็ encode มันให้เป็น Base64 แล้วก็ส่งไปใน Message Broker ให้ Service อื่นๆที่ต้องการใช้งาน ตัวอย่างโค้ดจะเป็นตัวอย่างง่ายๆ ในการแปลง image -> byte[] -> Base64 -> byte[] -> image นะครับ

สมมติว่าผมมี file /Users/chiwa.kantawong/tmp/images/pea.jpg

ผมต้องการส่งไฟล์นี้ไปยัง Service อื่นๆ โดยผ่าน Message Broker หรืออะไรก็แล้วแต่
ในที่นี้ผมจะแปลงเป็น Base64 แล้วก็แปลงกลับไปเป็น image ทีชื่อว่า copy.jpg เราจะไม่พูดถึงการส่งผ่านเครือข่ายใดๆ ในโค้ดนี้นะครับ

package sunseries.travel.request.handler.view;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

@Slf4j
public class TestBase64 {

public static void main(String[] args) throws IOException {

File file =
new File("/Users/chiwa.kantawong/tmp/images/pea.jpg");
byte[] bytes = fileToBytes(file);
//เราก็จะแปลง byte[] => Base64 String ที่สามารถส่งไปให้ service อื่นๆ แล้วนะครับ
String base64String = Base64.getEncoder()
.encodeToString(bytes);

//แปลง base64 -> image ครับ
byte[] byteArray = org.apache.commons.codec.binary
.Base64
.decodeBase64(base64String);

FileOutputStream fos =
new FileOutputStream("/Users/chiwa.kantawong/tmp/images/copy.jpg");
fos.write(byteArray);
fos.close();

}

private static byte[] fileToBytes(File file) throws IOException {
//init array with file length
byte[] bytesArray =
new byte[(int) file.length()];
FileInputStream fis =
new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
return bytesArray;
}
}

เมื่อเรารัน Application ข้างบนเราก็จะได้ไฟล์เพิ่มขึ้นมาดังรูปครับ

เอาไปประยุกต์ใช้กันนะครับ ซึ่งนี่ก็เป็นวิธีหนึ่งในการส่งไฟล์ต่างๆ ข้ามไปมาระหว่าง Service ซึ่งก็อาจจะมีวิธีอื่นๆ อีกมากมายแล้วแต่กรณีที่จะใช้นะครับ

--

--

Chiwa Kantawong (Pea)
Chiwa Kantawong (Pea)

Written by Chiwa Kantawong (Pea)

Software Development Expert at Central Tech

Responses (1)