::: facebook post , add image , code in react , ios , android

Great! Here’s how to create a Facebook-style post feature that supports text + image upload for:

✅ React (Web)
✅ iOS (React Native)
✅ Android (React Native)

You’ll get:

  • 📄 Input field (for post content)
  • 🖼️ Image picker / file upload
  • 📤 Submit button
  • ⚙️ Upload to backend (Node.js or Firebase)

🧱 1. 🔵 React (Web) — Facebook-style Post + Image

💻 PostForm.js (React)

jsx
import React, { useState } from 'react';

function PostForm() {
const [text, setText] = useState('');
const [image, setImage] = useState(null);

const handlePost = async () => {
const formData = new FormData();
formData.append('text', text);
if (image) formData.append('image', image);

await fetch('http://localhost:4000/upload', {
method: 'POST',
body: formData,
});

setText('');
setImage(null);
};

return (
<div>
<textarea value={text} onChange={e => setText(e.target.value)} />
<input type="file" accept="image/*" onChange={e => setImage(e.target.files[0])} />
<button onClick={handlePost}>Post</button>
</div>
);
}

export default PostForm;

📱 2. 🔴 iOS/Android (React Native)

Requires react-native-image-picker or expo-image-picker

With Expo (simplest way)

bash
expo install expo-image-picker

📱 React Native code:

jsx
import React, { useState } from 'react';
import { View, TextInput, Button, Image } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

export default function PostForm() {
const [text, setText] = useState('');
const [image, setImage] = useState(null);

const pickImage = async () => {
const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images });

if (!result.cancelled) {
setImage(result);
}
};

const handlePost = async () => {
const formData = new FormData();
formData.append('text', text);
if (image) {
formData.append('image', {
uri: image.uri,
name: 'photo.jpg',
type: 'image/jpeg',
});
}

await fetch('http://localhost:4000/upload', {
method: 'POST',
body: formData,
headers: { 'Content-Type': 'multipart/form-data' },
});

setText('');
setImage(null);
};

return (
<View>
<TextInput value={text} onChangeText={setText} placeholder="What's on your mind?" />
<Button title="Pick Image" onPress={pickImage} />
{image && <Image source={{ uri: image.uri }} style={{ width: 100, height: 100 }} />}
<Button title="Post" onPress={handlePost} />
</View>
);
}

⚙️ 3. Optional Backend (Node.js + Express)

js
const express = require('express');
const multer = require('multer');
const cors = require('cors');
const app = express();

app.use(cors());
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('image'), (req, res) => {
console.log('Text:', req.body.text);
console.log('Image:', req.file);
res.send({ status: 'ok' });
});

app.listen(4000, () => console.log('Server on port 4000'));

✅ Summary

PlatformMethod
React Web<input type="file"> + FormData()
iOS/Androidexpo-image-picker + FormData
BackendUse multer for image parsing

Would you like:

  • 🖼 Image preview grid (multiple images)?
  • 🔄 Real-time feed showing uploaded posts?
  • 🧠 Store posts to Firebase or MongoDB?

Let me know — I can build the full system for you.

native code of ios , android

ยอดเยี่ยมครับ! ด้านล่างนี้คือ ตัวอย่างโค้ด Native แยกตามแพลตฟอร์ม สำหรับการทำ “โพสต์ข้อความ + รูปภาพ” แบบ Facebook Messenger/Feed (upload ไปยัง backend):


🍎 iOS (Swift + UIKit)

✅ ฟีเจอร์:

  • พิมพ์ข้อความ
  • เลือกรูปภาพจากคลัง
  • อัปโหลดไปยัง server ด้วย multipart/form-data

📄 ViewController.swift

swift
import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

let textView = UITextView()
let imageView = UIImageView()
var selectedImage: UIImage?

override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white

textView.frame = CGRect(x: 20, y: 80, width: 340, height: 100)
textView.layer.borderWidth = 1
view.addSubview(textView)

imageView.frame = CGRect(x: 20, y: 200, width: 100, height: 100)
imageView.contentMode = .scaleAspectFill
view.addSubview(imageView)

let imageButton = UIButton(type: .system)
imageButton.frame = CGRect(x: 140, y: 200, width: 100, height: 44)
imageButton.setTitle("Choose Image", for: .normal)
imageButton.addTarget(self, action: #selector(pickImage), for: .touchUpInside)
view.addSubview(imageButton)

let postButton = UIButton(type: .system)
postButton.frame = CGRect(x: 20, y: 320, width: 100, height: 44)
postButton.setTitle("Post", for: .normal)
postButton.addTarget(self, action: #selector(uploadPost), for: .touchUpInside)
view.addSubview(postButton)
}

@objc func pickImage() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
present(picker, animated: true)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage {
selectedImage = image
imageView.image = image
}
dismiss(animated: true)
}

@objc func uploadPost() {
guard let url = URL(string: "http://localhost:4000/upload") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"

let boundary = UUID().uuidString
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

var body = Data()

// Text
let text = textView.text ?? ""
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"text\"\r\n\r\n")
body.append("\(text)\r\n")

// Image
if let image = selectedImage,
let imageData = image.jpegData(compressionQuality: 0.8) {
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"\r\n")
body.append("Content-Type: image/jpeg\r\n\r\n")
body.append(imageData)
body.append("\r\n")
}

body.append("--\(boundary)--\r\n")
request.httpBody = body

URLSession.shared.dataTask(with: request).resume()
}
}

// สำหรับแนบ Data จาก String
extension Data {
mutating func append(_ string: String) {
if let data = string.data(using: .utf8) {
append(data)
}
}
}

🤖 Android (Kotlin + XML)

✅ ฟีเจอร์:

  • EditText สำหรับข้อความ
  • ImageView + Button สำหรับเลือกรูป
  • อัปโหลดผ่าน Multipart ด้วย OkHttp

📄 activity_main.xml

xmlCopyEdit<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="16dp"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/editText"
        android:hint="What's on your mind?"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginTop="8dp"
        android:scaleType="centerCrop" />

    <Button
        android:id="@+id/selectImage"
        android:text="Choose Image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/postButton"
        android:text="Post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

📄 MainActivity.kt

kotlinCopyEditclass MainActivity : AppCompatActivity() {

    private lateinit var editText: EditText
    private lateinit var imageView: ImageView
    private var imageUri: Uri? = null

    private val pickImage =
        registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
            uri?.let {
                imageUri = it
                imageView.setImageURI(it)
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        editText = findViewById(R.id.editText)
        imageView = findViewById(R.id.imageView)

        findViewById<Button>(R.id.selectImage).setOnClickListener {
            pickImage.launch("image/*")
        }

        findViewById<Button>(R.id.postButton).setOnClickListener {
            uploadPost()
        }
    }

    private fun uploadPost() {
        val client = OkHttpClient()
        val text = editText.text.toString()

        val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
        builder.addFormDataPart("text", text)

        imageUri?.let { uri ->
            val inputStream = contentResolver.openInputStream(uri)
            val bytes = inputStream!!.readBytes()
            builder.addFormDataPart("image", "upload.jpg",
                bytes.toRequestBody("image/jpeg".toMediaTypeOrNull()))
        }

        val request = Request.Builder()
            .url("http://10.0.2.2:4000/upload") // ใช้ IP เครื่องจริงหากไม่ใช้ emulator
            .post(builder.build())
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("UPLOAD", "Failed: ${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                Log.i("UPLOAD", "Success")
            }
        })
    }
}

✅ Backend ที่ใช้ร่วมกัน

jsCopyEdit// Node.js + Express + Multer
const express = require('express');
const multer = require('multer');
const cors = require('cors');
const app = express();

app.use(cors());
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('image'), (req, res) => {
  console.log('Text:', req.body.text);
  console.log('Image file:', req.file);
  res.send({ status: 'success' });
});

app.listen(4000, () => console.log('Server running at port 4000'));

✅ สรุป

ระบบภาษาจุดเด่น
iOSSwift + UIKitใช้งาน UIImagePickerController, Upload แบบ Multipart
AndroidKotlinใช้ ActivityResult + OkHttp Multipart
ServerNode.jsใช้ Multer รับข้อความ + รูปภาพ

หากคุณต้องการ source code package หรือ demo พร้อม backend เต็มระบบ (รวม feed), แจ้งได้เลยครับ! ✅