天天看点

Js实现文件上传无刷新以及图片预览

JS想实现无刷新文件上传,还得使用iframe和form,通过在页面内放入一个内置form表单的iframe,让文件在上传的时候只发生局部刷新。

具体实现步骤:

1.首先在页面里定义iframe和form:

<body>

//自己的项目代码

//iframe随便定义在什么位置

<iframe name="uploadfrag" src="src/components/uploadfragment.html" frame scrolling="no" width="100%" height="100%"></iframe>

</body>

2.在uploadfragment.html中定义form表单和上传图片函数并实现上传预览

<body>

//注意enctype必写,上传文件的表单必须使用该格式

<form  id="uploadform" action="上传的地址" enctype="multipart/form-data" method="post">

<input  id="uploadimg" type="file" name="image"/>

<input type="hidden" name="要上传参数的字段名" value="要上传的参数的值"/>

<button class="upload-img-submit" type="submit" οnclick="upload()">确定</button>

</form>

</form>

<script>

var uli = document.getElementById("uli")

if(uli.addEventListener){

uli.addEventListener("change",function(){

var url = null ; 

var file = document.getElementById("uli").files[0]

if (window.createObjectURL!=undefined) { // basic

url = window.createObjectURL(file) ;

} else if (window.URL!=undefined) { // mozilla(firefox)

url = window.URL.createObjectURL(file) ;

} else if (window.webkitURL!=undefined) { // webkit or chrome

url = window.webkitURL.createObjectURL(file) ;

}

var img = document.createElement("img")

img.src = url

img.width = 200

img.height = 360

img.style.border = "1px solid #333"

img.style.marginTop = "15px"

document.getElementById("uploadform").appendChild(img)

})

}else{

uli.attachEvent("onChange",function(){

var url = null ; 

var file = document.getElementById("uli").files[0]

if (window.createObjectURL!=undefined) { // basic

url = window.createObjectURL(file) ;

} else if (window.URL!=undefined) { // mozilla(firefox)

url = window.URL.createObjectURL(file) ;

} else if (window.webkitURL!=undefined) { // webkit or chrome

url = window.webkitURL.createObjectURL(file) ;

}

var img = document.createElement("img")

img.src = url

img.width = 200

img.height = 360

img.style.border = "1px solid #333"

img.style.marginTop = "15px"

document.getElementById("uploadform").appendChild(img)

})

}

</script>

</body>

继续阅读