分享编程~
 

HTML PHP文件上传(二) iframe文件异步上传

form表单提交会跳转到新页面,通过iframe可以不刷新页面,实现表单内容及文件异步提交…

天天特卖抢好货

form表单提交会跳转到新页面,通过iframe可以不刷新页面,实现表单内容及文件异步提交。

实现原理是form提交到隐藏的iframe,监听iframe加载完成获得表单提交回调信息。

html如下:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>HTML文件上传(二) iframe文件异步上传</title>
    <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
	<div id="info"></div>
	<iframe name="demo_iframe" id="iframe_box" style="display:none"></iframe>
	<form target="demo_iframe" action="upload.php" method="post" enctype="multipart/form-data">
		<input type="file" name="file_name">
		<input type="submit" value="提交">
	</form>
	<script type="text/javascript">
		$('#iframe_box').on('load', function() {
			var responseText = $('iframe')[0].contentDocument.body.textContent;
			var responseData = JSON.parse(responseText) || {};
			if(responseData.code == 10000) {
				console.log('成功:'+responseData.path);
				$('#info').html('<img src="'+responseData.path+'" width="100" height="100" />');
			} else {
				console.log('失败:'+responseData.msg);
				$('#info').html('失败:'+responseData.msg);
			}
		});
    </script>
</body>
</html>


后端接收以php为例,upload.php 代码如下:

<?php 

// 文件上传方法
function file_upload(){
	$result = array('code'=>40000,'msg'=>'失败');
	if(!isset($_FILES) || !$_FILES){
		return $result;
	}
	$path = './uploads/'; // 上传路径
	$newname = date('YmdHis'); // 保存的文件名
	$suffix = strtolower(pathinfo($_FILES["file_name"]["name"], PATHINFO_EXTENSION)); // 文件后缀
	$newFilePath = $path.$newname.'.'.$suffix;

	// 将上传的文件移动到新位置
	if(!move_uploaded_file($_FILES["file_name"]["tmp_name"],$newFilePath)){
		$result['code'] = 30000;
		$result['msg'] = '文件上传出错了';
		return $result;
	}
	$result['code'] = 10000;
	$result['msg'] = '文件上传成功';
	$result['path'] = $newFilePath;
	return $result;
}

// 调用文件上传方法
$result = file_upload();
echo json_encode($result); 
return;

?>


上一篇:HTML PHP文件上传(一) 注意事项下一篇:HTML PHP文件上传(三) AJAX异步上传 文件base64上传js图片压缩
赞(0) 踩(0)
您说多少就多少,您的支持是我最大的动力
赏金
微 信
赏金
支付宝
本文连接: https://www.yj521.com/article/33.html
版权声明: 本文为原创文章,版权归《越加网》所有,分享转载请注明出处!