您的位置:首页 > 其它

ajax 上传图片预览

2015-09-14 23:16 369 查看
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">

<head>

<title>新建网页</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<meta name="description" content="" />

<meta name="keywords" content="" />

<style type="text/css">

img{

width:200px;

}

</style>

<script type="text/javascript">

//数据使用ajax 发送到另一个页面,不跳转

function fa(){

var fm = document.getElementById('aform');

var fd = new FormData(fm);

var xhr = new XMLHttpRequest();

xhr.open('POST','from.php',true);

xhr.onreadystatechange = function(){

if(this.readyState == 4){

document.getElementById('show').innerHTML = this.responseText;

}

}

xhr.send(fd);

}

//图片预览的函数,当点击 预览按钮时,调用

function prew(){

//获取文件对象

var pic = document.getElementsByName('pic')[0].files[0];

console.log(pic);

var fd = new FormData(); //html5中

fd.append('pic',pic); //将图片加到 formdata中

var tmpimg = document.createElement('img'); //创建img标签

tmpimg.src = window.URL.createObjectURL(pic); //创建img 的src属性,并赋值

document.getElementsByTagName('body')[0].appendChild(tmpimg);

//把img 标签 (强制)加载到body中显示;

}

</script>

</head>

<body>

<form id="aform">

<p>用户名<input type="text" name="user" >

<p>年龄<input type="text" name="age" >

<p>邮箱<input type="text" name="email" >

<input type="button" onclick="fa();" value="发送">

<p>

<input type="file" name="pic">

<input type="button" onclick="prew();" value="预览">

</form>

<div id="show"></div>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: