Effect preview
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];
const windowURL = window.URL || window.webkitURL;
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