Chào các bạn. Hôm nay mình sẽ hướng dẫn cho mọi người tạo nút upload ảnh lên Imgur bằng Javascript. Với code này bạn có thể tạo được công cụ upload ảnh lưu trữ trên Imgur để dùng mà không cần lưu trữ trực tiếp trên server giúp tiết kiệm dung lượng ổ đĩa.
Bước 1: Lấy API key imgur
Đầu tiên ae tạo cho mình một tài khoản imgur ở đây: Tạo tài khoản imgur
Sau khi tạo tài khoản imgur
Tiếp đến ae vào đây để tạo API key: Add Client – Imgur
Điền thông tin vào như này, có thể chọn callback để add callback url
Sau khi tạo xong API thì ae tiếp tục truy cập vào đây để lấy client ID: Preferences – Imgur
Client ID của mình sau khi tạo là 58f2ebf29687a0b
Vậy là ta đã có client ID – API key, tiếp theo là code nhé.
Bước 2: Code
Code javascript (Có jquery):
$('document').ready(function () {
$('input[type=file]').on('change', function () {
```var $files = $(this).get(0).files;
if ($files.length) {
if ($files[0].size > $(this).data('max-size') \* 1024) {
console.log('Vui lòng chọn file có dung lượng nhỏ hơn!');
return false;
}
console.log('Đang upload hình ảnh lên imgur...');
var apiUrl = 'https://api.imgur.com/3/image';
var apiKey = '58f2ebf29687a0b'; // Thay bằng Client ID của ae
var settings = {
async: false,
crossDomain: true,
processData: false,
contentType: false,
type: 'POST',
url: apiUrl,
headers: {
Authorization: 'Client-ID ' + apiKey,
Accept: 'application/json',
},
mimeType: 'multipart/form-data',
};
var formData = new FormData();
formData.append('image', $files[0]);
settings.data = formData;
$.ajax(settings).done(function (response) {
console.log(response);
});
}```
});
});
Ae thay apiKey thành client ID nhé
[HEADING=3]Code html:[/HEADING]
<script src="https://dl.dropboxusercontent.com/s/nvklmhq3kw4j9pq/jquerylasted.js?dl=0"></script>
<input type="file" accept="image/\*">
Vậy là ổn rồi, kết hợp 2 file trên và tận hưởng:
<script src="https://dl.dropboxusercontent.com/s/nvklmhq3kw4j9pq/jquerylasted.js?dl=0"></script>
<input type="file" accept="image/\*">
<script>
$('document').ready(function () {
$('input[type=file]').on('change', function () {
```var $files = $(this).get(0).files;
if ($files.length) {
if ($files[0].size > $(this).data('max-size') \* 1024) {
console.log('Vui lòng chọn file có dung lượng nhỏ hơn!');
return false;
}
console.log('Đang upload hình ảnh lên imgur...');
var apiUrl = 'https://api.imgur.com/3/image';
var apiKey = '58f2ebf29687a0b';
var settings = {
async: false,
crossDomain: true,
processData: false,
contentType: false,
type: 'POST',
url: apiUrl,
headers: {
Authorization: 'Client-ID ' + apiKey,
Accept: 'application/json',
},
mimeType: 'multipart/form-data',
};
var formData = new FormData();
formData.append('image', $files[0]);
settings.data = formData;
$.ajax(settings).done(function (response) {
console.log(response);
});
}```
});
});
</script>
Ae có thể vào đây để test code: Tryit Editor v3.6 (w3schools.com), lúc test nhớ mở console để xem kết quả nhé, dưới đây là kết quả trả về dạng json:
Kết quả thành công
Nhưng có một điều là ae phải tự xử lý json trả về, nên mình xử lý luôn cho ae dùng nhóe
Ae thêm một cái output ở html:
<div id="output"></div>
Và khi response được trả về thì thay vì console.log thì ae xài:
var obj = JSON.parse(response);
document.getElementById("output").innerHTML = obj.data.link;
Nếu ae muốn làm giống y đúc demo thì tải code dưới đây nhé, chúc ae thành công!
<script src="https://dl.dropboxusercontent.com/s/nvklmhq3kw4j9pq/jquerylasted.js?dl=0"></script>
<input type="file" accept="image/\*" >
<div id="output"></div>
<script>
$('document').ready(function () {
$('input[type=file]').on('change', function () {
```var $files = $(this).get(0).files;
if ($files.length) {
if ($files[0].size > $(this).data('max-size') \* 1024) {
console.log('Vui lòng chọn file có dung lượng nhỏ hơn!');
return false;
}
console.log('Đang upload hình ảnh lên imgur...');
var apiUrl = 'https://api.imgur.com/3/image';
var apiKey = '58f2ebf29687a0b';
var settings = {
async: false,
crossDomain: true,
processData: false,
contentType: false,
type: 'POST',
url: apiUrl,
headers: {
Authorization: 'Client-ID ' + apiKey,
Accept: 'application/json',
},
mimeType: 'multipart/form-data',
};
var formData = new FormData();
formData.append('image', $files[0]);
settings.data = formData;
$.ajax(settings).done(function (response) {
console.log(response);
var obj = JSON.parse(response);
document.getElementById("output").innerHTML = "<p>Chiều ngang: " + obj.data.width + " px<p></p>Chiều dọc: " + obj.data.height + " px<p></p>Size ảnh: " + obj.data.size + " byte<p></p>Đuôi ảnh: " + obj.data.type + "<p></p>Link ảnh: " + obj.data.link + "</p><p>Preview:</p><img src='"+ obj.data.link +"' style='width: 100%'>";
});
}```
});
});
</script>