js opens the resource manager (classic example: pure front-end selection and preview image)

Effect preview

insert image description here

Complete code example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>纯前端选择并预览图片</title>
</head>

<body>
    <button onclick="chooseImg()">选择图片</button>
    <div style="padding-top: 10px;">
        <img id="imgBox" width="100"></img>
    </div>

    <script>
        function chooseImg() {
      
      
            let input = document.createElement("input");
            input.setAttribute("type", "file");
            // 支持多选
            input.setAttribute("multiple", "multiple");
            input.accept = "image/*";
            input.addEventListener("change", (e) => {
      
      
                let file = e.path[0].files[0];
                // 浏览器兼容性处理(有的浏览器仅存在 Window.URL)
                const windowURL = window.URL || window.webkitURL;
                // createObjectURL 函数会根据传入的参数创建一个指向该参数对象的URL
                let filePath = windowURL.createObjectURL(file);
                document.getElementById("imgBox").setAttribute('src', filePath)
            });
            input.click();
        }
    </script>
</body>
</html>

Core Technology Analysis

  • Trigger the opening of the resource manager by creating a file input box node
  • Use the createObjectURL function to convert the selected image object into a URL, which is convenient for front-end rendering to display images

Guess you like

Origin blog.csdn.net/weixin_41192489/article/details/130379453