Trang chủ Share code Share code imgur API upload ảnh bằng javascript + Hướng dẫn

Share code imgur API upload ảnh bằng javascript + Hướng dẫn

bởi Sharescript.net

Để không tốn dung lượng ổ đĩa của website thì anh em có một cách đó là sử dụng dịch vụ lưu trữ bên thứ 3, ở đây mình sẽ hướng dẫn ae dùng API của imgur – một mạng xã hội chia sẻ hình ảnh cực lớn.

Xem demo trước nhé: https://sharescript.net/demo/imgur-upload-api/

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 sharescript 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é

Code html:

<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, link sau khi upload là https://i.imgur.com/v9dltnV.jpg

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!

[khungdownload manguon=”” redirectbanggi=”sharescript-redirect” tenfilezip=”imgur-api-javascript” linkbutton1=”https://sharescript.net/demo/imgur-upload-api/” tenbutton1=”Demo” linkbutton2=”https://github.com/phanminhtai/imgur-api-javascript/blob/main/index.html” tenbutton2=”Download”]

Đánh giá

Có thể bạn quan tâm

Website sử dụng cookie để cải thiện trải nghiệm của bạn Đồng ý Đọc thêm