JS报错:Cannot read property 'type' of undefined

时间:2021-02-16 16:19:01

在做图片上传功能的时候,遇到了JS无法识别图片type的问题,在使用过程中是没有问题的,但是不知道为什么浏览器的Console报这个错误:

Uncaught TypeError: Cannot read property 'type' of undefined
at Function.$.ImgSrc (ModelUpload.do:18)
at uploadImg (ModelUpload.do:77)
at HTMLInputElement.onchange (ModelUpload.do:110)

JS报错:Cannot read property 'type' of undefined
alert下面JS代码中的file[i].type的时候显示的是img/jpeg why???
页面相关代码如下:
HTML:

        <p>
<label for="picFileId">缩略图文件:</label> <input id="picFileId"
name="picFileId" type="file" onchange="uploadImg()" />
<fieldset>
<div style="position: relative;" id="fileImg"></div>
<legend>图片显示区域</legend>
</fieldset>
<p>

JS:

<script type="text/javascript">
$.ImgSrc = function(file, id) {
for (var i = 0; i < 3; i++) {
alert(file[i].type);
if (!/image\/\w+/.test(file[i].type)) { alert("请选择图片文件");
return false;
}
;
if (file[i].size > 2048 * 1024) {
alert("图片不能大于2M")
ClearImg();
continue;
}
;
var img;
console.log(document.getElementById("fileImg"));
console.log(file[i]);
console.log("file-size=" + file[i].size);
var reader = new FileReader();
reader.onloadstart = function(e) {
console.log("开始读取....");
}
reader.onprogress = function(e) {
console.log("正在读取中....");
}
reader.onabort = function(e) {
console.log("中断读取....");
}
reader.onerror = function(e) {
console.log("读取异常....");
}
reader.onload = function(e) {
console.log("成功读取....");
var div = document.createElement("div"); //外层 div
div
.setAttribute(
"style",
"position:relative;width:inherit;height:inherit;float:left;z-index:2;width:150px;margin-left:8px;margin-right:8px;");
var del = document.createElement("div"); //删除按钮div
del
.setAttribute(
"style",
"position: absolute; bottom: 4px; right: 0px; z-index: 99; width: 30px; height:30px;border-radius:50%;")
var delicon = document.createElement("img");
delicon.setAttribute("src", "images/shanchu.png");
delicon.setAttribute("title", "删除");
delicon.setAttribute("style",
"cursor:pointer;width: 30px; height:30px");
del.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentElement);
ClearImg();
};
del.appendChild(delicon);
div.appendChild(del);
var imgs = document.createElement("img"); //上传的图片
imgs.setAttribute("name", "loadimgs");
imgs.setAttribute("src", e.target.result);
imgs.setAttribute("width", 150);
//childNodes.length > 0 代表 最多传一张,再上传,就把前面的替换掉
if (document.getElementById(id).childNodes.length > 0) {
document.getElementById(id).removeChild(
document.getElementById(id).firstChild);
}
div.appendChild(imgs)
document.getElementById(id).appendChild(div);
}
reader.readAsDataURL(file[i]);
}
}
function uploadImg() {
$.ImgSrc(document.getElementById("picFileId").files, "fileImg");
}
function ClearImg() {
var file = $("#picFileId")
file.after(file.clone().val(""));
file.remove();
}
</script>

JS报错:Cannot read property 'type' of undefined >> java

这个答案描述的挺清楚的:
http://www.goodpm.net/postreply/java/1010000008888543/JS报错Cannotreadpropertytypeofundefined.html