檔案上傳 可以即時預覽


檔案上傳 可以即時預覽
https://progressbar.tw/posts/47

http://jsfiddle.net/sheephead0818/g7kydnd4/


https://ithelp.ithome.com.tw/articles/10164617

教你如何製作圖片上傳前的預覽圖
http://jsnwork.kiiuo.com/archives/2258/jquery-javascript-%E6%95%99%E4%BD%A0%E5%A6%82%E4%BD%95%E8%A3%BD%E4%BD%9C%E5%9C%96%E7%89%87%E4%B8%8A%E5%82%B3%E5%89%8D%E7%9A%84%E9%A0%90%E8%A6%BD%E5%9C%96

http://liuxiang.github.io/2017/04/01/javaScript%E5%89%8D%E7%AB%AF%E5%9B%BE%E7%89%87%E7%9B%B8%E5%85%B3%EF%BC%88%E9%A2%84%E8%A7%88%EF%BC%8C%E5%8E%8B%E7%BC%A9%EF%BC%8CBase64%EF%BC%8C%E4%B8%8A%E4%BC%A0%EF%BC%8C%E5%BC%82%E6%AD%A5%E5%8A%A0%E8%BD%BD%EF%BC%89/


<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>js圖片預覽功能</title> <script language=javascript> function previewFile() { var preview = document.querySelector('img'); var file = document.querySelector('input[type=file]').files[0]; var reader = new FileReader(); reader.onloadend = function () { preview.src = reader.result; } if (file) { reader.readAsDataURL(file); } else { preview.src = ""; } } </script> </head> <body> <input type="file" onchange="previewFile()"><br> <img src="" height="200" width="300" alt="Image preview..."/> </body> </html>
使用window.URL.createObjectURL(resText) 的 方法
http://www.cnblogs.com/liulangmao/p/4262565.html http://blog.darkthread.net/post-2014-03-12-html5-object-url.aspx http://blog.darkthread.net/post-2010-11-05-data-uri.aspx




利用 FileReader 讓瀏覽器讀取外部圖片檔案



來看看相關的程式碼,列舉如下:

<script>
            var file;
            var fileReader;
            function cfile_change() {
                file = document.getElementById('cfile').files[0];
                if (file) {
                    fileReader = new FileReader();
                    fileReader.onload = openfile;
                    readFileContent() ;
                }
            }
            function openfile(event) {
                document.getElementById('imgx').src = event.target.result;              
            }
            function readFileContent() {
                fileReader.readAsDataURL(file);
            }
</script>

當使用者完成圖片檔案的選取,會執行 cfile_change() 這個 change 事件處理器,建立一個 FileReader 物件,並且註冊其 load 事件處理器,最後調用 readAsDataURL() ,讀取參數file-也就是圖片的內容,最後於回呼函式 openfile() 中,取得圖片的 url 位址,將其設定給畫面上的 <img> 標籤 src 屬性,呈現圖片內容。

如果將其中的 event.target.result 取出,顯示出來結果內容如下:



當FileReader讀取圖片完成載入,回傳的是圖片的位址,這段位址表示圖片的所在位置,當然你不需要去理解它的內容只需將其設定給 img 元素的 src 屬性即可。

留言

這個網誌中的熱門文章

Use Case Description(描述使用案例)

列出不重複的隨機亂數

子類別建構子super觀念