Code javascript đơn giản giúp bạn tạo một trang web upload ảnh lên nền tảng Imgbb. Để tải lên hình ảnh lên Imgbb bằng XHR (XMLHttpRequest), bạn cần sử dụng API mà Imgbb cung cấp. Sau đây là các bước hướng dẫn cụ thể:
Các bước thực hiện
Bước 1: Lấy API Key của Imgbb
1. Truy cập trang web Imgbb API và đăng ký tài khoản (nếu chưa có).
2. Lấy API Key từ tài khoản của bạn.
Bước 2: Chuẩn Bị File HTML
Tạo một file HTML đơn giản để tải lên hình ảnh:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload to Imgbb</title>
</head>
<body>
<h1>Upload Image to Imgbb</h1>
<form id="upload-form">
<input type="file" id="image" accept="image/\*">
<button type="submit">Upload</button>
</form>
<p id="response"></p>
<script src="upload.js"></script>
</body>
</html>
Bước 3: Xử Lý JavaScript
Tạo file upload.js và dán đoạn code sau vào:
document.getElementById('upload-form').addEventListener('submit', function (e) {
e.preventDefault();
// Lấy file từ input
const fileInput = document.getElementById('image');
const file = fileInput.files[0];
if (!file) {
alert('Please select a file!');
return;
}
// API key của bạn
const apiKey = 'YOUR_IMGBB_API_KEY';
const apiUrl = \`https://api.imgbb.com/1/upload?key=${apiKey}\`;
// Tạo FormData
const formData = new FormData();
formData.append('image', file);
// Tạo XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('POST', apiUrl, true);
// Lắng nghe sự kiện
xhr.onload = function () {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
document.getElementById('response').textContent = \`Image URL: ${response.data.url}\`;
} else {
document.getElementById('response').textContent = \`Error: ${xhr.responseText}\`;
}
};
xhr.onerror = function () {
alert('Upload failed. Please try again.');
};
// Gửi request
xhr.send(formData);
});
Giải Thích Code
1. HTML:
• Input file để người dùng chọn ảnh.
• Nút bấm để thực hiện upload.
2. JavaScript:
• FormData: Dùng để gửi file dưới dạng multipart/form-data.
• XHR:
• Mở một request POST đến URL API.
• Gửi dữ liệu qua xhr.send(formData).
• Xử lý phản hồi từ server và hiển thị URL của ảnh đã upload.
3. API Key:
• API key từ Imgbb cần được thay thế vào "YOUR_IMGBB_API_KEY".
Chạy Dự Án
1. Lưu file index.html và upload.js vào cùng thư mục.
2. Mở file index.html bằng trình duyệt.
3. Chọn ảnh và nhấn “Upload”. Kết quả (URL của ảnh) sẽ hiển thị ở phần phản hồi.
Chúc các bạn thành công.