将个人资料图片上传到一个html页面,然后在没有数据库的情况下将其显示到下一个html页



我可以使用表单中的文件输入标记将图像上传到第一个网页。但我想在单击"提交"按钮时在另一个页面上显示相同的图像。

`

`<div class="profile-pic-div" id="input_field">
<input type="file" class="myfile" id="imgfile" accept="image/png, image/jpg">
</div>`

这是我在评论中描述的功能版本。

您可以使用FileReader()读取文件输入的值,并使用readAsDataURL方法将图像转换为DataURL。然后可以将其存储在localStorage中,然后在不同的页面上读取(假设所有页面都在同一域/站点上(。

不幸的是,StackSnippets在读取文件和localStorage等方面存在限制。这同样适用于像CodePen和jsfiddle这样的地方。正因为如此,我不能发布实时演示,但我可以给你源代码。

注意:同样,此StackSnippet演示在StackOverflow上不起作用。StackOverflow限制对localStorage和文件读取器等内容的访问。您需要在保存的.html文件中尝试此操作。

<!doctype html>
<html>
<head>
<title>Save Uploaded Image in LocalStorage</title>
<style>
input[type="file"] {
vertical-align: middle;
padding: 1em 2em;
border: 1px solid #CCC;
border-radius: 0.4em;
}
.save {
font-size: 1.2em;
vertical-align: middle;
padding: 0.6em 1em;
}
img {
max-width: 10em;
max-height: 10em;
}
</style>
</head>
<body>
<div id="status">Waiting...</div>
<input type="file" id="file" onchange="_ReadImage()">
<br>
<br>
<img id="img">
<br>
<input type="button" value="Load Image" onclick="_LoadImage()">
<br>
<br>
<br>
<br>
<p>Clicking <a href="javascript:location.reload();">this link</a> just reloads the page, but should <i>simulate</i> going to a new page where you could load the image data via localStorage.</p>
<script>
const _ReadImage = () => {
document.querySelector("#status").innerText = `Reading File...`;
let f = document.querySelector("#file");
if(f.files && f.files[0]) {
var reader = new FileReader();
reader.onload = e => {
_SaveImage(e.target.result);
}
reader.readAsDataURL(f.files[0]);
}
}
const _SaveImage = img => {
localStorage.setItem("img", img);
document.querySelector("#status").innerText = `Saved!`;
}
const _LoadImage = () => {
if(localStorage.getItem("img")) {
document.querySelector("#img").src = localStorage.getItem("img");
document.querySelector("#status").innerText = `Image Loaded!`;
} else {
document.querySelector("#status").innerText = `No Image!`;
}
}
</script>
</body>
</html>

最新更新