簡體   English   中英

將個人資料圖片上傳到一個html頁面,然后在沒有數據庫的情況下顯示到下一個html頁面

[英]Upload a profile picture to one html page and then display it to the next html page without database

能夠使用表單中的文件輸入標簽將圖像上傳到第一個 web 頁面。 但是當我單擊提交按鈕時,我想在另一個頁面上顯示相同的圖像。

`

 `<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM