php+jquery利用FormData上传图片~麻麻再也不担心图片要单独传了~
来源:傲雪星枫文件1:index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title> FormData Demo </title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
<!--
function fsubmit(){
var data = new FormData($('#form1'));
$.ajax({
url: 'server.php',
type: 'POST',
data: data,
dataType: 'JSON',
cache: false,
processData: false,
contentType: false
}).done(function(ret){
if(ret['isSuccess']){
var result = '';
result += '运行时间=' + ret['yunxing'] + '<br>';
result += 'name=' + ret['name'] + '<br>';
result += 'gender=' + ret['gender'] + '<br>';
result += '<img src="' + ret['photo']+ '" width="300">';
$('#result').html(result);
}else{
alert('提交失敗');
}
});
return false;
}
-->
</script>
</head>
<body>
<form name="form1" id="form1">
<p>图片和数据~可以一起传了^_^o ~~~</p>
<p>姓名:<input type="text" name="name" ></p>
<p>性别:<input type="radio" name="gender" value="1">哥哥<input type="radio" name="gender" value="2">妹子</p>
<p>头像:<input type="file" name="photo" id="photo"></p>
<p><input type="button" name="b1" value="提交"></p>
</form>
<div id="result"></div>
</body>
</html>
文件2:server.php
<?php
//程序运行时间
$starttime = explode(' ',microtime());
//echo microtime();
$name = isset($_POST['name'])? $_POST['name'] : '';
$gender = isset($_POST['gender'])? $_POST['gender'] : '';
$filename = 'img/'.rand(1000,9999).time().substr($_FILES['photo']['name'], strrpos($_FILES['photo']['name'],'.'));
$response = array();
if(move_uploaded_file($_FILES['photo']['tmp_name'], $filename)){
$response['isSuccess'] = true;
$response['name'] = $name;
$response['gender'] = $gender;
$response['photo'] = $filename;
}else{
$response['isSuccess'] = false;
}
//程序运行时间
$endtime = explode(' ',microtime());
$thistime = $endtime+$endtime-($starttime+$starttime);
$response['yunxing']="本网页执行耗时:".$thistime." 秒。";
echo json_encode($response);
?>
不明觉厉 JS文件呢? szhy007 发表于 2015-2-16 00:42
JS文件呢?
//code.jquery.com/jquery-1.11.0.min.js
页:
[1]