簡單的前端上傳圖片代碼


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>圖片上傳</title>

    <style type="text/css">
    /*
    css
     */
    #fileimg{
        width:200px;
        height:200px;
        border:1px solid #eee;
    }
    .Btn{
        width:100px;
        background: #4BCD61;
        border: 0px;
    }
    </style>
    <script type="text/javascript">
    //JS
    function fileClick() {
    document.getElementById('file').click()
    }//觸發一個觸發瀏覽事件,沒有的話點擊button就不會出現選擇框了

    function upCh(file){
        let img = document.getElementById('fileimg')
    let formData = new FormData()
    let imgUrl = file.files[0];
    if (imgUrl){
        formData.append('file',imgUrl);
        imgUrl.src = window.URL.createObjectURL(imgUrl)//window.URL.createObjectURL預覽圖片
       /*
        這里可以寫上傳到后端代碼
        */
    }
}

    </script>

</head>
<body>
<input type="file" id="file" name="" onchange="upCh(this)" />
<br />
<img id="fileimg" src="" />
<br />
<button class="Btn" onclick="fileClick()">上傳圖片</button>
</body>
</html>

此代碼可以復制粘貼看看運行效果,十分簡單

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM