繁体   English   中英

从 js 中的 unsplash Api 下载图像

[英]download image from unsplash Api in js

我正在使用 unsplash api 来显示图像。当用户单击下载图标时,我想下载图像。但我不知道如何添加此功能。这是我到目前为止所做的。在下面的代码中,我获取图像从 unsplash api 并使用显示网格将它们显示在 imageContainer 中...

  • 这是我的 html*
    <!-- image container -->
    <div class="imageContainer grid mt-10 p-2"></div>

    <!-- image popup container -->
    <div class="container height content z-20">
      <div class="icons">
        <i class="fa-solid fa-arrow-down downloadIcon"></i>
        <i class="fa-solid fa-xmark crossIcon"></i>
      </div>
      <div class="imgShowed imgfit z-20"></div>
    </div>
 
  • 这是我的 js*

let imageContainer = document.querySelector(".imageContainer");
let imgShowed = document.querySelector(".imgShowed");
let container = document.querySelector(".container");
let crossIcon = document.querySelector(".crossIcon");
let downloadIcon = document.querySelector(".downloadIcon")
// function to fetch image
function getimage() {
  imageContainer.innerHTML = "";
  (url =
    "https://api.unsplash.com/search/photos?query=" +
    input.value +
    "&per_page=1200&client_id=5OXcnxdQpZLtAG0_jRNpqEQhTlUOQL3TKviFAUbBKm8"),
    fetch(url)
      .then((response) => {
        return response.json();
      })
      .then((data) => {
    
        data.results.forEach((element) => {
          let Div = document.createElement("Div");
          Div.setAttribute("class", "imgDiv");
          Div.setAttribute("data-downloadurl", `${element.links.download}`);
          let img = document.createElement("img");
          img.src = `${element.urls.regular}`;
          Div.appendChild(img);
          document.querySelector(".imageContainer").appendChild(Div);
          imagepopup()
        });
      });
}
document.getElementById("btn").addEventListener("click", getimage);

// image popup function
function imagepopup(){
  let imgDiv = document.querySelectorAll(".imgDiv");
  imgDiv.forEach(element => {
    element.addEventListener("click",(e)=>{
      container.style.display="block"
      let target = e.currentTarget
      let clickedimagesrc = target.firstChild.src
      imgShowed.innerHTML=`<img src="${clickedimagesrc}" class="imgfit" alt="...">`
      downloadIcon.addEventListener("click",()=>{
        let url=target.dataset.downloadurl
        downloadIMG(url)
      })
    })
  });
}

function downloadIMG(){
  const link = document.createElement('a');
  link.style.display = 'none';
    link.href = URL.createObjectURL(url);
    link.download = file.name;
    link.click();
}

我目前正在使用 Vuejs,但您可以将其调整为适合您的。 您需要将下载的 imageUrl 转换为 blob 并使用 window.URL.createObjectURL 方法获取 url。

在锚标记中使用生成的 URL 并使用下载属性。

<a :href="imageDownloadUrl" :download="idModal">Download</a>


data() {
    return {
        imageDownloadUrl: "",
    };
},

methods: {
    async toDataURL(url) {
        const response = await fetch(url);
        const blob = await response.blob();
        const imageUrl = window.URL.createObjectURL(blob);
        // console.log(imageUrl);
        this.imageDownloadUrl = imageUrl;
    },

    getImageUrl(id) {
        const url = this.$store.state.baseURL;
        const key = this.$store.state.apiKey;
        const ixid =
            "MnwxMTc4ODl8MHwxfHNlYXJjaHwxfHxwdXBweXxlbnwwfHx8fDE2MTc3NTA2MTM";

        const endpoint = `${url}/photos/${id}/download?ixid=${ixid}&client_id=${key}`;

        // the endpoint it's like: https://api.unsplash.com/photos/imageId/download?ixid=ixId&client_id=apiKey
        
        // the full path can be found in **links.download_location** of the returned array of images, also get your **ixid** from the link and make sure to include apiKey.

        axios
            .get(endpoint)
            .then((response) => {
                let url = response.data.url;
                this.toDataURL(url);
            })
            .catch((error) => {
                console.log(error);
            });
    },
},

注意:如果您使用下面链接中的示例,请尽量不要返回 window.URL.createObjectURL(blob)因为您将有一个承诺,但由于您只需要url只需将其保存到变量并使用它作为具有下载属性的锚标记的href值(如上)...下载属性值是可选的。

有用的网址:

Vanilla js 实现: 如何使用 ReactJs 创建一个从 API 获取图像并下载到本地的按钮

下载带有锚标签的文件: 如何使 PDF 文件可在 HTML 链接中下载?

createObjectURL 解释: https ://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM