当我们需要使用input的file做图片上传时候,想要看一下上传的图片,该如何实现呢?
具体实现有两种方法
1、使用readAsDataURL
function handleChange() {
const myFile = document.querySelector("input[type=file]").files[0];
const img = new Image();
const reader = new FileReader(); // 读取文件资源
if (myFile) {
reader.readAsDataURL(myFile);//将上传图片转成base64地址
} else {
img.src = "";
}
reader.onload = function () {
img.src = reader.result;
};
const imgHeader = document.getElementById("header");
const childNodeList = document.querySelectorAll("img");
if (childNodeList.length > 0) {
for (let i = 0; i < childNodeList.length; i++) {
imgHeader.removeChild(childNodeList[i]);
}
}
imgHeader.insertBefore(img, document.querySelector("input[type=file]"));
}
2、使用URL.createObjectURL
function handleChange() {
const myFile = document.querySelector("input[type=file]").files[0];
const img = new Image();
const objUrl=URL.createObjectURL(myFile);
img.src=objUrl;
img.onload=function(){
window.URL.revokeObjectURL(objUrl);
}
const imgHeader = document.getElementById("header");
const childNodeList = document.querySelectorAll("img");
if (childNodeList.length > 0) {
for (let i = 0; i < childNodeList.length; i++) {
imgHeader.removeChild(childNodeList[i]);
}
}
imgHeader.insertBefore(img, document.querySelector("input[type=file]"));
}
注意:如果使用createObjectURL创建图片地址,记得要使用revokeObjectURL清除掉
<header className="App-header" id="header">
<input
type="file"
accept="image/*"
onChange={handleChange}
id="myFile"
/>
</header>
效果
如果上传还有pdf格式,需要预览可以借助html5新增的embed标签,将生成地址给embed的src属性。