ข้ามไปยังเนื้อหาหลัก

Cloud Storage

อัปโหลดไฟล์โดยตรงไปยังผู้ให้บริการ cloud storage โดยไม่ต้องผ่านเซิร์ฟเวอร์ของคุณ

Amazon S3

การติดตั้ง

npm install @samithahansaka/dropup

การใช้งานพื้นฐาน

import { useDropup } from '@samithahansaka/dropup';
import { createS3Uploader } from '@samithahansaka/dropup/cloud/s3';

function S3Uploader() {
const { files, actions, getDropProps, getInputProps } = useDropup({
upload: createS3Uploader({
getPresignedUrl: async (file) => {
// เรียก backend ของคุณเพื่อรับ presigned URL
const response = await fetch('/api/s3/presign', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
filename: file.name,
contentType: file.type,
}),
});
return response.json();
},
}),

onUploadComplete: (file) => {
console.log('อัปโหลดไปยัง S3:', file.uploadedUrl);
},
});

return (
<div {...getDropProps()}>
<input {...getInputProps()} />
<p>วางไฟล์เพื่ออัปโหลดไปยัง S3</p>
</div>
);
}

Backend: สร้าง Presigned URL

// ตัวอย่าง Node.js / Express
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

const s3 = new S3Client({
region: process.env.AWS_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
});

app.post('/api/s3/presign', async (req, res) => {
const { filename, contentType } = req.body;
const key = `uploads/${Date.now()}-${filename}`;

const command = new PutObjectCommand({
Bucket: process.env.S3_BUCKET,
Key: key,
ContentType: contentType,
});

const url = await getSignedUrl(s3, command, { expiresIn: 3600 });

res.json({
url,
fields: {}, // สำหรับ PUT แบบง่าย ไม่ต้องมี fields เพิ่มเติม
});
});

S3 พร้อม POST (Multipart Form)

สำหรับ S3 POST policies:

createS3Uploader({
getPresignedUrl: async (file) => {
const response = await fetch('/api/s3/presign-post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
filename: file.name,
contentType: file.type,
}),
});

const { url, fields } = await response.json();

return {
url, // S3 bucket URL
fields, // Policy fields ที่จะรวมใน form
};
},
});

Google Cloud Storage

import { createGCSUploader } from '@samithahansaka/dropup/cloud/gcs';

function GCSUploader() {
const { files, getDropProps, getInputProps } = useDropup({
upload: createGCSUploader({
getSignedUrl: async (file) => {
const response = await fetch('/api/gcs/sign', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
filename: file.name,
contentType: file.type,
}),
});
return response.json();
},
}),
});

return (
<div {...getDropProps()}>
<input {...getInputProps()} />
<p>อัปโหลดไปยัง Google Cloud Storage</p>
</div>
);
}

Backend: GCS Signed URL

// ตัวอย่าง Node.js
import { Storage } from '@google-cloud/storage';

const storage = new Storage();
const bucket = storage.bucket(process.env.GCS_BUCKET);

app.post('/api/gcs/sign', async (req, res) => {
const { filename, contentType } = req.body;
const blob = bucket.file(`uploads/${Date.now()}-${filename}`);

const [url] = await blob.getSignedUrl({
version: 'v4',
action: 'write',
expires: Date.now() + 15 * 60 * 1000, // 15 นาที
contentType,
});

res.json({ url });
});

Azure Blob Storage

import { createAzureUploader } from '@samithahansaka/dropup/cloud/azure';

function AzureUploader() {
const { files, getDropProps, getInputProps } = useDropup({
upload: createAzureUploader({
getSasUrl: async (file) => {
const response = await fetch('/api/azure/sas', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
filename: file.name,
contentType: file.type,
}),
});
return response.json();
},
}),
});

return (
<div {...getDropProps()}>
<input {...getInputProps()} />
<p>อัปโหลดไปยัง Azure Blob Storage</p>
</div>
);
}

Backend: Azure SAS URL

// ตัวอย่าง Node.js
import {
BlobServiceClient,
generateBlobSASQueryParameters,
BlobSASPermissions,
} from '@azure/storage-blob';

const blobServiceClient = BlobServiceClient.fromConnectionString(
process.env.AZURE_STORAGE_CONNECTION_STRING
);

app.post('/api/azure/sas', async (req, res) => {
const { filename, contentType } = req.body;
const containerClient = blobServiceClient.getContainerClient('uploads');
const blobName = `${Date.now()}-${filename}`;
const blobClient = containerClient.getBlockBlobClient(blobName);

const sasToken = generateBlobSASQueryParameters(
{
containerName: 'uploads',
blobName,
permissions: BlobSASPermissions.parse('cw'), // สร้าง, เขียน
expiresOn: new Date(Date.now() + 15 * 60 * 1000),
},
blobServiceClient.credential
).toString();

res.json({
url: `${blobClient.url}?${sasToken}`,
headers: {
'x-ms-blob-type': 'BlockBlob',
'Content-Type': contentType,
},
});
});

Cloudflare R2

R2 รองรับ S3-compatible ดังนั้นใช้ S3 uploader:

import { createS3Uploader } from '@samithahansaka/dropup/cloud/s3';

function R2Uploader() {
const { files, getDropProps, getInputProps } = useDropup({
upload: createS3Uploader({
getPresignedUrl: async (file) => {
const response = await fetch('/api/r2/presign', {
method: 'POST',
body: JSON.stringify({ filename: file.name }),
});
return response.json();
},
}),
});

return (
<div {...getDropProps()}>
<input {...getInputProps()} />
<p>อัปโหลดไปยัง Cloudflare R2</p>
</div>
);
}

Backend: R2 Presigned URL

import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

const s3 = new S3Client({
region: 'auto',
endpoint: `https://${process.env.CF_ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: process.env.R2_ACCESS_KEY_ID,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
},
});

app.post('/api/r2/presign', async (req, res) => {
const { filename } = req.body;

const command = new PutObjectCommand({
Bucket: process.env.R2_BUCKET,
Key: `uploads/${Date.now()}-${filename}`,
});

const url = await getSignedUrl(s3, command, { expiresIn: 3600 });
res.json({ url });
});

DigitalOcean Spaces

รองรับ S3-compatible เช่นกัน:

// เหมือนกับ S3 แค่อัปเดตการกำหนดค่า endpoint ของ backend
const s3 = new S3Client({
region: 'nyc3',
endpoint: 'https://nyc3.digitaloceanspaces.com',
credentials: {
accessKeyId: process.env.DO_SPACES_KEY,
secretAccessKey: process.env.DO_SPACES_SECRET,
},
});

Custom Cloud Provider

สร้าง uploader ของคุณเองสำหรับบริการ cloud ใดๆ:

import { useDropup, type CustomUploader } from '@samithahansaka/dropup';

const customCloudUploader: CustomUploader = async (file, options) => {
// 1. รับ upload URL จาก backend ของคุณ
const { uploadUrl, fileUrl } = await fetch('/api/custom-cloud/init', {
method: 'POST',
body: JSON.stringify({ filename: file.name, size: file.size }),
}).then(r => r.json());

// 2. อัปโหลดไฟล์
const xhr = new XMLHttpRequest();

return new Promise((resolve, reject) => {
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
options.onProgress((e.loaded / e.total) * 100);
}
};

xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({ url: fileUrl });
} else {
reject(new Error('อัปโหลดล้มเหลว'));
}
};

xhr.onerror = () => reject(new Error('ข้อผิดพลาดเครือข่าย'));

// จัดการการยกเลิก
options.signal.addEventListener('abort', () => xhr.abort());

xhr.open('PUT', uploadUrl);
xhr.send(file.file);
});
};

function CustomCloudUploader() {
const { files, getDropProps, getInputProps } = useDropup({
upload: customCloudUploader,
});

return (
<div {...getDropProps()}>
<input {...getInputProps()} />
<p>อัปโหลดไปยัง cloud แบบกำหนดเอง</p>
</div>
);
}

แนวทางปฏิบัติด้านความปลอดภัยที่ดี

  1. อย่าเปิดเผย credentials บนไคลเอนต์ - สร้าง signed URLs บน backend เสมอ
  2. ใช้เวลาหมดอายุสั้น - 5-15 นาทีมักเพียงพอ
  3. ตรวจสอบประเภทไฟล์บน backend - อย่าพึ่งพาการตรวจสอบฝั่งไคลเอนต์เพียงอย่างเดียว
  4. ตั้งค่า CORS policies ที่เหมาะสม บน cloud storage ของคุณ
  5. จำกัดขนาดไฟล์ ใน presigned URL policies ของคุณ
  6. ใช้ buckets แยก สำหรับการอัปโหลดของผู้ใช้ vs. assets ของแอปพลิเคชัน