天天看點

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>

繼續閱讀