欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在?localStorage?中上傳和檢索存儲圖像的示例詳解

 更新時(shí)間:2022年06月13日 14:31:32   作者:allway2  
這篇文章主要介紹了在?localStorage?中上傳和檢索存儲圖像,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

我參與過許多項(xiàng)目,這些項(xiàng)目要求用戶上傳單張或一組照片,然后他們可以以某種方式對其進(jìn)行操作,無論是添加過濾效果還是變形他們的臉以進(jìn)行電視節(jié)目宣傳。

在這些項(xiàng)目中的任何一個(gè)中,用戶上傳的照片都必須保留一段特定的時(shí)間 - 足夠長的時(shí)間讓用戶可以操作他們的圖像。從 GDPR 和發(fā)展的角度來看,一直存在的問題是:用戶上傳的照片應(yīng)該存儲多長時(shí)間?

以前,這些照片存儲在云中的臨時(shí) blob 存儲容器中,每小時(shí)任務(wù)刪除超過 6 小時(shí)的圖像。這也確保了存儲容器的尺寸保持較小,從而降低了使用成本。

然后有一天,它擊中了我......如果用戶上傳的照片可以在任何形式的操作之前通過他們自己的瀏覽器存儲在本地怎么辦?進(jìn)入本地存儲...

什么是本地存儲?

本地存儲允許將數(shù)據(jù)作為鍵/值對存儲在瀏覽器中。此數(shù)據(jù)沒有設(shè)置的到期日期,并且在關(guān)閉瀏覽器時(shí)不會被清除。只有字符串值可以存儲在本地存儲中 - 這不是問題,我們將在這篇文章中看到我們將如何存儲一組圖像以及每個(gè)圖像的一些數(shù)據(jù)。

示例:存儲照片集

這個(gè)例子的前提是允許用戶上傳一組照片。成功上傳后,他們的照片將被渲染,并且能夠從收藏中刪除照片。添加和刪??除照片也會導(dǎo)致瀏覽器的 localStorage 更新。

此頁面的現(xiàn)場演示可以在我的 JSFiddle 帳戶上找到:https ://jsfiddle.net/sbhomra/bts3xo5n/ 。

代碼

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Storing Images in Local Storage</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>
            <h1>
                Example: Storing Images in Local Storage
            </h1>
            <input id="image-upload" type="file" />
            <ul id="image-collection">
            </ul>
        </div>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="script.js"></script>
    </body>
</html>

JavaScript

const fileUploadLimit = 1048576; // 1MB in bytes. Formula: 1MB = 1 * 1024 * 1024.
const localStorageKey = "images";
let imageData = [];
 
// Render image in HTML by adding to the unordered list.
function renderImage(imageObj, $imageCollection) {
  if (imageObj.file_base64.length) {
    $imageCollection.append("<li><img src=\"data:image/png;base64," + imageObj.file_base64 + "\"  width=\"200\" /><br />" + imageObj.name + "<br /><a href=\"#\" data-timestamp=\"" + imageObj.timestamp + "\" class=\"btn-delete\">Remove</a></li>")
  }
}
 
// Add image to local storage.
function addImage(imageObj) {
  imageData.push(imageObj);
  localStorage.setItem(localStorageKey, JSON.stringify(imageData));
}
 
// Remove image from local storage by timestamp.
function removeImage(timestamp) {
  // Remove item by the timestamp.
  imageData = imageData.filter(img => img.timestamp !== timestamp);
 
  // Update local storage.
  localStorage.setItem(localStorageKey, JSON.stringify(imageData));
}
 
// Read image data stored in local storage.
function getImages($imageCollection) {
  const localStorageData = localStorage.getItem(localStorageKey);
 
  if (localStorageData !== null) {
    imageData = JSON.parse(localStorage.getItem(localStorageKey))
 
    for (let i = 0; i < imageData.length; i++) {
      renderImage(imageData[i], $imageCollection);
    }
  }
}
 
// Delete button action to fire off deletion.
function deleteImageAction() {
  $(".btn-delete").on("click", function(e) {
    e.preventDefault();
 
    removeImage($(this).data("timestamp"));
 
    // Remove the HTML markup for this image.
    $(this).parent().remove();
  })
}
 
// Upload action to fire off file upload automatically.
function uploadChangeAction($upload, $imageCollection) {
  $upload.on("change", function(e) {
    e.preventDefault();
 
    // Ensure validation message is removed (if one is present).
    $upload.next("p").remove();
 
    const file = e.target.files[0];
 
    if (file.size <= fileUploadLimit) {
      const reader = new FileReader();
 
      reader.onloadend = () => {
        const base64String = reader.result
          .replace('data:', '')
          .replace(/^.+,/, '');
 
        // Create an object containing image information.
        let imageObj = {
          name: "image-" + ($imageCollection.find("li").length + 1),
          timestamp: Date.now(),
          file_base64: base64String.toString()
        };
 
        // Add To Local storage
        renderImage(imageObj, $imageCollection)
        addImage(imageObj);
 
        deleteImageAction();
 
        // Clear upload element.
        $upload.val("");
      };
 
      reader.readAsDataURL(file);
    } else {
      $upload.after("<p>File too large</p>");
    }
  });
}
 
// Initialise.
$(document).ready(function() {
  getImages($("#image-collection"));
 
  // Set action events.
  uploadChangeAction($("#image-upload"), $("#image-collection"));
  deleteImageAction();
});

要查看的關(guān)鍵功能是:

  • 添加圖片 ()
  • 刪除圖像()
  • 獲取圖像()

這些函數(shù)中的每一個(gè)都使用 JSON 方法將上傳的照片存儲為對象數(shù)組。每張照片包含:名稱、時(shí)間戳和一個(gè) base64 字符串。這些函數(shù)中使用的一個(gè)常見功能是使用 JSON 方法來幫助我們將照片集合存儲在本地存儲中:

  • JSON.stringify() - 將數(shù)組轉(zhuǎn)換為字符串。
  • JSON.parse() - 將 JSON 字符串轉(zhuǎn)換為對象數(shù)組以進(jìn)行操作。

從本地存儲中保存或檢索保存的值時(shí),需要通過“鍵”設(shè)置唯一標(biāo)識符。在我的示例中,我設(shè)置了以下在需要使用“localStorage”方法時(shí)引用的全局變量。

const localStorageKey = "images";

保存到 localStorage 時(shí),我們必須對對象數(shù)組進(jìn)行字符串化:

localStorage.setItem(localStorageKey, JSON.stringify(imageData));

檢索我們的數(shù)組需要我們將值從字符串轉(zhuǎn)換回對象:

imageData = JSON.parse(localStorage.getItem(localStorageKey))

在我們上傳了一些圖片之后,我們可以通過進(jìn)入您的瀏覽器(對于 Firefox)Web 開發(fā)人員工具,導(dǎo)航到“存儲”選項(xiàng)卡并選擇您的站點(diǎn)來查看存儲的內(nèi)容。如果使用 Chrome,請轉(zhuǎn)到“應(yīng)用程序”選項(xiàng)卡并單擊“本地存儲”。

存儲限制

可以存儲的值的最大長度因?yàn)g覽器而異。數(shù)據(jù)大小目前介于 2MB 和 10MB 之間。

當(dāng)我決定使用本地存儲來存儲用戶照片時(shí),我擔(dān)心超出存儲限制,因此我將每張照片的上傳限制設(shè)置為 1MB。當(dāng)我有機(jī)會在真實(shí)場景中使用我的代碼時(shí),我打算使用Hermite Resize來實(shí)現(xiàn)一些圖像壓縮和調(diào)整大小的技術(shù)。

到此這篇關(guān)于在 localStorage 中上傳和檢索存儲圖像的文章就介紹到這了,更多相關(guān)localStorage存儲圖像內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論