1. 程式人生 > >從本地上傳圖片

從本地上傳圖片

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>html5實現上傳</title>
<style type="text/css">
#result{
width: 200px;
height:112px;
border:1px solid #eee;
}
#result img{
width: 1rem;
}
input{
width: 70px;
margin-top: 10px;
}
@-moz-document url-prefix() { input { width:65px; } }/*單獨對火狐進行設定*/
</style>
</head>
<body>
<div id = "result"></div>
<input id="pic" type="file" name = 'pic' accept = "image/*" onchange = "selectFile()"/>
<!-- <button onclick = "handIn()">提交</button> -->
<script type="text/javascript">
//var files = document.getElementById('pic').files;
var form = new FormData();//通過HTML表單建立FormData物件
var url = '127.0.0.1:8080/'
function selectFile(){
var files = document.getElementById('pic').files;
console.log(files[0]);
if(files.length == 0){
return;
}
var file = files[0];
//把上傳的圖片顯示出來
var reader = new FileReader();
// 將檔案以Data URL形式進行讀入頁面
console.log(reader);
reader.readAsBinaryString(file);
reader.onload = function(f){
var result = document.getElementById("result");
var src = "data:" + file.type + ";base64," + window.btoa(this.result);
result.innerHTML = '<img src ="'+src+'"/>';
}
console.log('file',file);
///////////////////
form.append('file',file);
console.log(form.get('file'));
}
//var xhr = new XMLHttpRequest();
// function handIn(){
// console.log(form.get('file'));
// xhr.open("post", url, true);
// xhr.addEventListener("readystatechange", function() {
// var result = xhr;
// if (result.status != 200) { //error
// console.log('上傳失敗', result.status, result.statusText, result.response);
// }
// else if (result.readyState == 4) { //finished
// console.log('上傳成功', result);
// }
// });
// }
</script>
</body>
</html>