在?localStorage?中上傳和檢索存儲圖像的示例詳解
我參與過許多項(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)文章
JS 在數(shù)組插入字符的實(shí)現(xiàn)代碼(可參考JavaScript splice() 方法)
在數(shù)組插入字符,添加數(shù)組,刪除數(shù)組可以用slice自帶的方法。操作比較方便,這個(gè)代碼是作者通過push與shift方法實(shí)現(xiàn),只能是個(gè)思路,但不推薦這樣的方法。2009-12-12JS實(shí)現(xiàn)添加,替換,刪除節(jié)點(diǎn)元素的方法
這篇文章主要介紹了JS實(shí)現(xiàn)添加,替換,刪除節(jié)點(diǎn)元素的方法,實(shí)例分析了javascript針對節(jié)點(diǎn)元素的替換、刪除及常用的幾種添加技巧,需要的朋友可以參考下2016-06-06javascript實(shí)現(xiàn)的元素拖動函數(shù)宿主為瀏覽器
這篇文章主要介紹了javascript實(shí)現(xiàn)的元素拖動,將相應(yīng)的元素對象的引用傳到函數(shù)中2014-07-07js實(shí)現(xiàn)prototype擴(kuò)展的方法(字符串,日期,數(shù)組擴(kuò)展)
這篇文章主要介紹了js實(shí)現(xiàn)prototype擴(kuò)展的方法,實(shí)例分析了JavaScript針對字符串、日期、數(shù)組等的prototype擴(kuò)展相關(guān)技巧,需要的朋友可以參考下2016-01-01bootstrap jquery dataTable 異步ajax刷新表格數(shù)據(jù)的實(shí)現(xiàn)方法
這篇文章主要介紹了bootstrap jquery dataTable 異步ajax刷新表格數(shù)據(jù)的實(shí)現(xiàn)方法,需要的朋友可以參考下2017-02-02javascript實(shí)現(xiàn)根據(jù)身份證號讀取相關(guān)信息
這篇文章主要介紹了javascript實(shí)現(xiàn)根據(jù)身份證號讀取相關(guān)信息,需要的朋友可以參考下2014-12-12js實(shí)現(xiàn)的八點(diǎn)拖動修改div大小的代碼
八點(diǎn)改變div大小的實(shí)現(xiàn)代碼,代碼相對來說并不多,需要的朋友可以參考下。2010-02-02微信小程序?qū)崿F(xiàn)分享商品海報(bào)功能
這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)分享商品海報(bào)功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09