当前位置:网站首页>在 localStorage 中上传和检索存储图像
在 localStorage 中上传和检索存储图像
2022-06-13 06:45:00 【allway2】
我参与过许多项目,这些项目要求用户上传单张或一组照片,然后他们可以以某种方式对其进行操作,无论是添加过滤效果还是变形他们的脸以进行电视节目宣传。
在这些项目中的任何一个中,用户上传的照片都必须保留一段特定的时间 - 足够长的时间让用户可以操作他们的图像。从 GDPR 和发展的角度来看,一直存在的问题是:用户上传的照片应该存储多长时间?
以前,这些照片存储在云中的临时 blob 存储容器中,每小时任务删除超过 6 小时的图像。这也确保了存储容器的尺寸保持较小,从而降低了使用成本。
然后有一天,它击中了我......如果用户上传的照片可以在任何形式的操作之前通过他们自己的浏览器存储在本地怎么办?进入本地存储...
什么是本地存储?
本地存储允许将数据作为键/值对存储在浏览器中。此数据没有设置的到期日期,并且在关闭浏览器时不会被清除。只有字符串值可以存储在本地存储中 - 这不是问题,我们将在这篇文章中看到我们将如何存储一组图像以及每个图像的一些数据。
示例:存储照片集
这个例子的前提是允许用户上传一组照片。成功上传后,他们的照片将被渲染,并且能够从收藏中删除照片。添加和删除照片也会导致浏览器的 localStorage 更新。
此页面的现场演示可以在我的 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();
});
要查看的关键功能是:
- 添加图片 ()
- 删除图像()
- 获取图像()
这些函数中的每一个都使用 JSON 方法将上传的照片存储为对象数组。每张照片包含:名称、时间戳和一个 base64 字符串。这些函数中使用的一个常见功能是使用 JSON 方法来帮助我们将照片集合存储在本地存储中:
- JSON.stringify() - 将数组转换为字符串。
- JSON.parse() - 将 JSON 字符串转换为对象数组以进行操作。
从本地存储中保存或检索保存的值时,需要通过“键”设置唯一标识符。在我的示例中,我设置了以下在需要使用“localStorage”方法时引用的全局变量。
const localStorageKey = "images";
保存到 localStorage 时,我们必须对对象数组进行字符串化:
localStorage.setItem(localStorageKey, JSON.stringify(imageData));
检索我们的数组需要我们将值从字符串转换回对象:
imageData = JSON.parse(localStorage.getItem(localStorageKey))
在我们上传了一些图片之后,我们可以通过进入您的浏览器(对于 Firefox)Web 开发人员工具,导航到“存储”选项卡并选择您的站点来查看存储的内容。如果使用 Chrome,请转到“应用程序”选项卡并单击“本地存储”。
存储限制
可以存储的值的最大长度因浏览器而异。数据大小目前介于 2MB 和 10MB 之间。
当我决定使用本地存储来存储用户照片时,我担心超出存储限制,因此我将每张照片的上传限制设置为 1MB。当我有机会在真实场景中使用我的代码时,我打算使用Hermite Resize来实现一些图像压缩和调整大小的技术。
边栏推荐
- 【马尔科夫链-蒙特卡罗】马尔科夫链-蒙特卡罗方法对先验分布进行抽样
- Eureka server multi node deployment
- Common method of props changing value V-model sync
- Gold jewelry enterprise operation mode, beautiful tiantians business solution
- [Collection des questions d'examen les plus complètes de Tencent Ali] (quatre côtés: 3 tours de technologie + 1 tour de RH)
- 时间格式化工具----moment.js(网页时间实时展示)
- Differences between SQL and NoSQL of mongodb series
- Notes on wechat applet development
- Project analysis of Taishan crowdfunding mode: why is Taishan crowdfunding mode so popular?
- 髋关节MR详细图谱(转载)
猜你喜欢
ML之FE:Vintage曲线/Vintage分析的简介、计算逻辑、案例应用之详细攻略
[virtual machine] VMware virtual machine occupies too much space. Solution
'ipconfig' is not an internal or external command, nor is it a runnable program or batch file.
As the new trend of blind box e-commerce, how can the platform use blind box play to drain at low cost?
MySQL系列之分库分表学习笔记
How to quickly support the team leader to attract new fission users in the business marketing mode of group rebate?
Jinglianwen Technology: current situation and solutions of data acquisition and labeling industry
[SketchUp 2021] sketch master's image output and rendering style description [edge setting, plane setting, background setting, watermark setting, modeling setting, sky background creating sky, creatin
JS case Xiaomi second kill countdown New Year Countdown
数据在内存中的存储(C语言)
随机推荐
Jfinal uses freemaker to output map.
Eureka server multi node deployment
Ijkplayer code walk through H264 unpacker application details
景联文科技:数据采集标注行业现状及解决方案
1154. 一年中的第几天
Base64 principle
Command line for database
数据在内存中的存储(C语言)
Why is the new e-commerce outlet mode so popular? What is the specific mode?
MongoDB系列之SQL和NoSQL的区别
How to make a development board from scratch? Illustrated and illustrated, step by step operation for you to see.
That is, after the negative impact of gcat advertising e-commerce, is there no stable advertising e-commerce platform?
Kotlin collaboration - simple use of collaboration
Detailed explanation of scrcpy client code walk through H264 raw stream decoding process
Scrcpy development environment construction and source code reading
Cocos creator compilation game cannot read property 'polygonpolygon' of undefined
105. constructing binary trees from preorder and inorder traversal sequences
Kotlin basic objects, classes and interfaces
Kotlin base generics
16、 IO stream (II)