Как сохранить изображения в формате imgur api с помощью ajax - PullRequest
0 голосов
/ 30 апреля 2019

Я пытаюсь загрузить изображения gif на сервер imgur, используя ajax.Код работает нормально для PNG и JPG.но когда я пытаюсь прикрепить изображения в формате gif, в ответ мне выдается URL-адрес файла png.ниже приведен код

 image.onload = function() {


                var MAX_WIDTH = 500;
                var MAX_HEIGHT = 500;
                var tempW = image.width;
                var tempH = image.height;
                if (tempW > tempH) {
                    if (tempW > MAX_WIDTH) {
                        tempH *= MAX_WIDTH / tempW;
                        tempW = MAX_WIDTH;
                    }
                } else {
                    if (tempH > MAX_HEIGHT) {
                        tempW *= MAX_HEIGHT / tempH;
                        tempH = MAX_HEIGHT;
                    }
                }
                var canvas = document.createElement("canvas");
                canvas.width = tempW;
                canvas.height = tempH;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(this, 0, 0, tempW, tempH);
                dataURL = canvas.toDataURL();
                dataURL = dataURL.replace(/^data:image\/(png|jpg|gif);base64,/, "");

                $.ajax({
                    url: 'https://api.imgur.com/3/image',
                    type: 'post',
                    headers: {
                        Authorization: 'Client-ID *************'
                    },
                    data: {
                        image: dataURL
                    },
                    dataType: 'json',
                    error: function(response) {

                        console.log(response);

                    },
                    success: function(response) {
                        if (response.success) {
                            console.log(response.data.link);

                            $('#snippet_image').val(response.data.link);
                        }
                    }
                });
            }

Что я пробовал, я добавил gif с помощью png | jpg, как показано ниже

dataURL = dataURL.replace(/^data:image\/(png|jpg|gif);base64,/, "");

1 Ответ

0 голосов
/ 01 мая 2019

Привет, вам не хватает multipart / form-data, mime-тип в вашем примере ajax:

html:

<form id="imgur">
  <input type="file" class="imgur" accept="image/*" data-max-size="5000"/>
</form>

js:

$("document").ready(function() {

  $('input[type=file]').on("change", function() {

    var $files = $(this).get(0).files;

    if ($files.length) {

      // Reject big files
      if ($files[0].size > $(this).data("max-size") * 1024) {
        console.log("Please select a smaller file");
        return false;
      }

      // Begin file upload
      console.log("Uploading file to Imgur..");

      // Replace ctrlq with your own API key
      var apiUrl = 'https://api.imgur.com/3/image';
      var apiKey = 'ctrlq';

      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;

      // Response contains stringified JSON
      // Image URL available at response.data.link
      $.ajax(settings).done(function(response) {
        console.log(response);
      });

    }
  });
});

исходный код: ссылка

Надеюсь, это поможет

...