iframe实现Ajax文件上传效果示例
程序员文章站
2023-08-26 10:58:32
复制代码 代码如下:
<span style="font-family: verdana, 'ms song', 宋体, arial, 微软雅黑, helvetica, sans-serif; font-size: 14px; line-height: 21px; text-align: left; background-color: rgb(255, 254, 247); ">avascript部分</span>
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<head>
<title>ajax 文件上传~~</title>
</head>
<script>
window.onload=function(){
var form=document.getelementsbytagname('form')[0];
form.onsubmit=function(){
var iframe=document.createelement('iframe');
iframe.src='do_upload.php';
var iframe_name="iframe"+math.random();
iframe.name=iframe_name;
document.body.appendchild(iframe);
iframe.style.width='0px';
iframe.style.height='0px';
iframe.frameborder='0';
form.target=iframe_name;
}
}
</script>
<body>
<form enctype='multipart/form-data' method='post' action='do_upload.php'>
请选择文件:<input type='file' name='myfile'/><br/>
<input type='submit'/>
<div id='msg'></div>
</form>
</body>
</html>
//php接收部分
<?php
$up_file=$_files['myfile'];
if($up_file['error']===0){
if(!file_exists('./imgs')){
mkdir('./imgs');
}
$save_name=rand().$up_file['name'];
$bool=move_uploaded_file($up_file['tmp_name'],"./imgs/$save_name");
if($bool){
$msg='上传成功!';
}else{
$msg='上传失败!';
}
}
echo
"<script>
var msg=parent.document.getelementbyid('msg');
msg.innerhtml='<font color=red>$msg</forn>';
</script>";
?>
复制代码 代码如下:
<span style="font-family: verdana, 'ms song', 宋体, arial, 微软雅黑, helvetica, sans-serif; font-size: 14px; line-height: 21px; text-align: left; background-color: rgb(255, 254, 247); ">avascript部分</span>
复制代码 代码如下:
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<head>
<title>ajax 文件上传~~</title>
</head>
<script>
window.onload=function(){
var form=document.getelementsbytagname('form')[0];
form.onsubmit=function(){
var iframe=document.createelement('iframe');
iframe.src='do_upload.php';
var iframe_name="iframe"+math.random();
iframe.name=iframe_name;
document.body.appendchild(iframe);
iframe.style.width='0px';
iframe.style.height='0px';
iframe.frameborder='0';
form.target=iframe_name;
}
}
</script>
<body>
<form enctype='multipart/form-data' method='post' action='do_upload.php'>
请选择文件:<input type='file' name='myfile'/><br/>
<input type='submit'/>
<div id='msg'></div>
</form>
</body>
</html>
//php接收部分
复制代码 代码如下:
<?php
$up_file=$_files['myfile'];
if($up_file['error']===0){
if(!file_exists('./imgs')){
mkdir('./imgs');
}
$save_name=rand().$up_file['name'];
$bool=move_uploaded_file($up_file['tmp_name'],"./imgs/$save_name");
if($bool){
$msg='上传成功!';
}else{
$msg='上传失败!';
}
}
echo
"<script>
var msg=parent.document.getelementbyid('msg');
msg.innerhtml='<font color=red>$msg</forn>';
</script>";
?>
上一篇: 这年头真的是什么人都有