亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 JavaScript 檢查圖像 URL?

如何使用 JavaScript 檢查圖像 URL?

幕布斯6054654 2021-11-12 15:35:18
所以我試圖檢查圖像 URL 是否有效,它必須返回一個true或false值。問題是我不知道如何實現這一點。我正在使用 ionic 4.0,這就是我已經擁有的:imageExists(url, callback) {   const img = new Image();   img.onload = function () { callback(true); };   img.onerror = function () { callback(false); };   if(callback === true ) {     return true;    } else {      return false;    }}  const imageUrl = 'https://www.google.com/images/srpr/nav_logo14.png';  let bool = this.imageExists(imageUrl, function (exists) {    console.log('RESULT: url=' + imageUrl + ', exists=' + exists);    console.log(exists);    bool = exists;  });console.log(bool);
查看完整描述

3 回答

?
莫回無

TA貢獻1865條經驗 獲得超7個贊

您可以使用一些正則表達式來實現這一點。


function validURL(str) {

  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol

    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name

    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address

    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path

    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string

    '(\\#[-a-z\\d_]*)?$','i'); // fragment locator

  return !!pattern.test(str);

}


查看完整回答
反對 回復 2021-11-12
?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

你很接近,但你需要設置img.src = url開始嘗試加載:)另外,刪除檢查if (callback === true)因為這沒有意義;callback 是一個函數,而不是一個布爾值。布爾值作為 onload / onerror 處理程序中的參數傳遞給函數。


查看完整回答
反對 回復 2021-11-12
?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

通過獲取圖像本身來檢查怎么樣,有效的 url 實際上不是真實的圖像,你可以這樣做的方式,也許通過這樣做


const contentTypePart = "image";

const isImage = (url) => new Promise((resolve, reject) => {

  // check that is a valid url

  // then if valid url

  fetch(url).then((response) => {

    if (response.ok) {

      const currentContentType = response.headers.get('Content-Type');

      // check if the content type is actually an image extension

      if (currentContentType.indexOf(contentTypePart) > -1) {

        return resolve(url);

      }

    }

    reject(false);

  }).catch(reject)

})

或者如果您更喜歡使用 Image 構造函數


const contentTypePart = "image";

const isImage = (url) => new Promise((resolve, reject) => {

  // check that is a valid url

  // then if valid url

  const image = new Image();

  image.src = url;

  image.onload = resolve;

  image.onerror = reject;

});

最后的使用方法是


isImage('https://www.google.com/').then(console.log.bind(null, 'is a valid image')).catch(console.error.bind(null, 'is not a valid image'))

上面的代碼會拋出一個,console.error因為 url 是一個網站而不是一個圖像。


通過這樣做,您可以檢查該 url 實際上是一個真實有效的圖像。


查看完整回答
反對 回復 2021-11-12
  • 3 回答
  • 0 關注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號