jquery ajax通过FormData上传图片或文件
[ 2017/07/05, JavaScript , 3752阅, 0评 ]

QQ截图20170705232105.jpg

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
<dd>姓名:<input type="text" id="name"></dd>
<dd>电话:<input type="text" id="phone"></dd>
<dd>内容:<textarea id="content"></textarea></dd>
<dd>文件:<input type="file" id="myfile" accept="image/jpg,image/jpeg,image/png,image/gif"/></dd>
<dd><img id="showImage" src="" style="width:200px;height:auto"></dd>
<dd><input type="button" id="mybtn" value="提交"></dd>
<script src="jquery-1.11.1.min.js"></script>
<script>
var myfile,
	myjson = {};
$("#myfile").change(function(e){
	myfile = e.target.files[0];
	//myfile = $(this)[0].files[0];
	//生成缩略图
    var reader = new FileReader();
    reader.onload = (function(){
        return function(){
            $("#showImage")[0].src=this.result;
        };
    })(myfile);
    reader.readAsDataURL(myfile);
});
$("#mybtn").click(function(){
	var myFormData = new FormData();
	myjson = {
		name: $("#name").val(),
		phone: $("#phone").val(),
		content: $("#content").val(),
		photo: myfile
	};
	for(var x in myjson){
		myFormData.append(x, myjson[x]);
	}
	$.ajax({
		url: "yourapi.php",
		type: "POST",
		dataType: "json",
		data: myFormData,
		cache: false,//上传文件不需要缓存
		contentType: false,//告诉jQuery不要去设置ContentType请求头
		processData: false,//告诉jQuery不要去处理发送的数据
		beforeSend: function(){
			//showLoad(true);显示加载动画
		},success: function(res){
			//showLoad(false);隐藏加载动画
		},error: function(){
			//showLoad(false);隐藏加载动画
		}
	});
});
</script>
</body>
</html>

yourapi.php代码:

<?php 
$name = isset($_POST['name'])? $_POST['name'] : '';
$phone = isset($_POST['phone'])? $_POST['phone'] : '';
$content = isset($_POST['content'])? $_POST['content'] : '';

$filename = 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['phone'] = $phone;
	$response['content'] = $content;
	$response['photo'] = $filename;
}else{
	$response['isSuccess'] = false;
}
echo json_encode($response);  
?>

Servlet 3.0开始,可以通过request.getPart()或request.getPars()两个接口获取上传的文件。

相关文档:

1、使用FormData对象提交表单及上传图片

2、JQuery Ajax使用FormData对象上传文件 图片

有朋自远方来...评论一下呗O(∩_∩)O