Diễn đàn » PHP - HTML - CSS » Upload ảnh lên imgur thông qua Cloudflare khi imgur bị chặn ở VN
Avatar
tờ ròm Tôi yêu Việt Nam
- API đích:https://api.imgur.com/3/image.json
- Môi trường trung gian: Cloudflare workers
- Code bên phía Cloudflare workers:
export default {
  async fetch(request) {
    const client_id = 'api key của bạn';
    const corsHeaders = { 'Access-Control-Allow-Origin': 'http://domaincuaban' };

    if (request.method === 'OPTIONS') {
      return new Response(null, {
        status: 204,
        headers: {
          ...corsHeaders,
          'Access-Control-Allow-Methods': 'POST, OPTIONS',
          'Access-Control-Allow-Headers': 'Content-Type, Authorization',
          'Access-Control-Max-Age': '86400'
        }
      });
    }

    if (request.method !== 'POST') {
      return new Response('Only POST allowed', { status: 405, headers: corsHeaders });
    }

    try {
      const formData = await request.formData();
      const imgurRes = await fetch('https://api.imgur.com/3/image.json', {
        method: 'POST',
        headers: {
          'Authorization': `Client-ID ${client_id}`,
          'Accept': 'application/json',
          'User-Agent': 'Cloudflare-Workers/1.0'
        },
        body: formData
      });

      return new Response(await imgurRes.text(), {
        status: imgurRes.status,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      return new Response(JSON.stringify({ error: 'Failed to connect to Imgur' }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  }
}


- Code javascript bên phía Client:
function imgur(f, ob) {
    var files = document.querySelector(f);
    files.onchange = function () {
        var file = this.files[0];
        if (file && file.type.match(/image.*/)) {
            var fd = new FormData();
            fd.append("image", file);
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "https://domaincuaban.workers.dev");
            xhr.upload.onprogress = function (e) {
                if (e.lengthComputable) {
                    var percent = Math.floor((e.loaded / e.total) * 100) + '%';
                    ob.loading(percent);
                }
            };
            xhr.onload = function () {
                var res = JSON.parse(xhr.responseText);
                if (res.success === true && res.status === 200) {
                    var data = res.data;
                    ob.loaded(data.link, data.type, data.size, data.datetime);
                } else {
                    window.alert('Lỗi: tải lên thất bại');
                }
            };
            xhr.send(fd);
        } else {
            window.alert('Chỉ cho phép chọn ảnh');
        }
    };
}
Trống!
Trống!
  • BBcode:
  • Markdown: