File控制項選擇圖片的時候在Html5下馬上預覽

來源:互聯網
上載者:User

標籤:選擇圖片   使用   jquery   svg   load   Enctype   jpg   target   init   

頁面HTML

    <div>        <img src="@pic.Path" id="img" style="width:200px;height:200px;" />        <form id="form_photo" method="post" action="/N/SavePhoto?id=1">            <input style=" display:none" type="file" name="file" id="file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" />            <input type="hidden" name="HeadImg" />            <input type="button" value="提交" onclick="savePhoto(1)" />        </form>    </div>

JS

/*=============File控制項選擇圖片的時候在Html5下馬上預覽=================*/    function InitFile(fileId, imgId) {        $("#" + imgId).click(function () {            $("#" + fileId).trigger("click");        });        document.getElementById(fileId).onchange = function (evt) {            // 如果瀏覽器不支援FileReader,則不處理              if (!window.FileReader) return;            var files = evt.target.files;            for (var i = 0, f; f = files[i]; i++) {                if (!f.type.match(‘image.*‘)) {                    continue;                }                var reader = new FileReader();                reader.onload = (function (theFile) {                    return function (e) {                        // img 元素                          document.getElementById(imgId).src = e.target.result;                    };                })(f);                reader.readAsDataURL(f);            }        }    }    InitFile("file", "img"); //h5選擇圖片載入

註:由於

accept="image/*"的緣故,使用Google瀏覽器開啟圖片檔案,響應5~6S(效果不佳,IE瀏覽器不會--秒開)
尋找資料之後修改成
accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
但也一樣(IE瀏覽器不會--秒開),有高見的請求支援

還有就是,form表單提交檔案的話,需要加個enctype="multipart/form-data",
我是使用AJAX提交的(這個需要引用jquery-form.js)

本人新手小白,只是寫一寫記錄,感謝指導我的大大。

File控制項選擇圖片的時候在Html5下馬上預覽

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.