ZardoZAntony

imageLoader

May 20th, 2022 (edited)
422
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  const imageLoader = {
  2.             img: null,
  3.  
  4.             createPreviewImage: function () {
  5.                 this.img = document.createElement("img");
  6.                 this.img.classList.add("w-100");
  7.                 this.img.classList.add("mb-1");
  8.                 this.img.style.maxWidth = '350px';
  9.                 this.img.setAttribute('id', 'preview_image');
  10.             },
  11.  
  12.             showImage: function () {
  13.                 $('#preview_image').remove();
  14.                 $('#btn_image').before(this.img);
  15.             },
  16.  
  17.             fetchImageFileByUrl: async function (url) {
  18.                 const fileName = url.split("/").pop();
  19.                 const fileExt = url.split(".").pop();
  20.  
  21.                 const data = await fetch(url);
  22.                 const buffer = await data.arrayBuffer();
  23.                 const blob = new Blob([buffer]);
  24.                 return new File([blob], fileName, {type: "image/" + fileExt});
  25.             },
  26.  
  27.             loadFileToFileInput: function (fileInput, file) {
  28.                 const tmp = new ClipboardEvent('').clipboardData || new DataTransfer();
  29.                 tmp.items.add(file);
  30.                 fileInput.files = tmp.files;
  31.             },
  32.  
  33.             loadImageByCategoryId: function (id) {
  34.                 this.createPreviewImage();
  35.  
  36.                 $.get('/api/category/' + id + '/get_image', async function (fileUrl) {
  37.                     const file = await this.fetchImageFileByUrl(fileUrl);
  38.                     const fileInput = $('#image')[0];
  39.  
  40.                     this.loadFileToFileInput(fileInput, file);
  41.                     this.img.src = fileUrl;
  42.                     this.showImage();
  43.                 }.bind(this))
  44.             }
  45.         }
Add Comment
Please, Sign In to add comment