PHP如何使用AJAX上传文件?

qqaazzqq2009 2010-07-28 01:41:45
我想在PHP简单的上传文件的基础中添加AJAX方式的上传,请问我该怎么做?
...全文
681 点赞 收藏 6
写回复
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
床上等您 2010-07-28
AJAX不能上传。
但可以模拟ajax上传,即无刷新上传

主要是利用一个 隐藏的 iframe 来实现。
回复
kyzy_yy_pm 2010-07-28
下面代码运行在应用了smarty模板的程序中,不是类似模板的话请修改后应用,头几天在网上下jquery的上传插件,不知道为什么老出错,后来自己弄出一个比较难看的来,呵呵,既回答了楼主的问题(比一定被选),也希望猛男们指出其中不足


//html代码

<form action="index.php?act=a" method="post" enctype="multipart/form-data" target="frame" id="form">
<input type="file" name="file" class="input">
<input type="submit" name="submit_upload" value="上 传">
<iframe id="frame" name="frame" width="0" height="0" marginwidth="0" frameborder="0" src="about:blank"></iframe>
</form>
<div id="div">
<% section name=loop loop=$return_data %>
<div id="div<% $return_data[loop].num %>"><img src="<% $return_data[loop].imgpath %>" height="100"><a id="a<% $return_data[loop].num %>" onclick="del(<% $return_data[loop].num %>)" style="cursor:pointer;">删除</a></div>
<% /section %>
</div>
<input type="hidden" id="name">
<input type="hidden" id="imgpath">
<input type="hidden" id="num">

<script>
var request;
function createxmlHttpRequest(){
if(!request){
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
}
}

function callback(num){
if (request.readyState == 4){
if (request.status == 200){
// alert(request.responseText);
parent.document.getElementById("div" + num).innerHTML = "";
parent.document.getElementById("div" + num).style.display = "none";
}else if(request.status == 404){
alert("该路径未找到");
}else if(request.status == 403){
alert("禁止访问");
}else{
alert("status is " + request.status);
}
}
}

function del(num){
createxmlHttpRequest();
var url = "index.php";
var send = "act=a&submit_delete=1&num=" + num;
request.open("post", url, true);
request.onreadystatechange = function(){
callback(num);
}
request.setRequestHeader("content-type", "application/x-www-form-urlencoded");
request.send(send);
}
</script>


//php代码

<?php
//================================================================================
function p($var){echo '<pre>';if(!$var){var_dump($var);}else{print_r($var);}exit;}
//================================================================================
/*---------------------------------------------------------------
* data 数组,包含元素如下:
* -------------------------------------------------------------
* sub_type 提交类型:upload-添加上传图片 delete-删除上传图片
* -------------------------------------------------------------
* file 上传图片的$_FILES['filename']
* -------------------------------------------------------------
* img_dir 图片上传的路径(相对路径)
* -------------------------------------------------------------
* num 图片上传/删除的标识
* -------------------------------------------------------------
*/
function upload($data){
$num = $data['num'];
if(!$data['file'] && $data['sub_type'] != 'delete'){
echo 'file_not_isnull';exit;
}
if(!$data['img_dir']){
echo 'pic_savepath_isnull';exit;
}
if(!isset($data['max_file_size'])){
$data['max_file_size'] = 1024 * 1024;
}else{
$data['max_file_size'] = $data['max_file_size'] * 1024 * 1024;
}
if(!isset($data['type_array'])){
$data['type_array'] = array('image/pjpeg', 'image/jpeg', 'image/gif');
}
if(!isset($data['sub_type'])){
$data['sub_type'] = 'upload';
}

$imgpath = '';
if(isset($data['sub_type']) && $data['sub_type'] == 'delete'){
if(isset($_SESSION['img'][$data['num']]['name']) && $_SESSION['img'][$data['num']]['name']){
if(is_file($_SESSION['img'][$data['num']]['imgpath'])){
$b = unlink($_SESSION['img'][$data['num']]['imgpath']);
}
unset($_SESSION['img'][$data['num']]);
if(!isset($_SESSION['img'][$data['num']]['name'])){
echo 'del_ok';
}else{
echo 'del_no';
}
}else{
echo 'no_pic';
}exit;
}

if(!in_array($data['file']['type'], $data['type_array'])){
echo 'pic_type_no';exit;
}
if($data['file']['size'] > $data['max_file_size']){
echo 'pic_size_toobig';exit;
}

if(!is_dir($data['img_dir'])){
mkdir($data['img_dir'], 0777, true);
}
$imgpath = $data['img_dir'].'/'.date('His', time()).rand(100, 999).$data['file']['name'];
$isupload = move_uploaded_file($data['file']['tmp_name'], $imgpath);
if(!$isupload){
echo 'pic_upload_no';exit;
}
$_SESSION['img'][$num]['name'] = $data['file']['name'];
$_SESSION['img'][$num]['imgpath'] = $imgpath;
$_SESSION['img'][$num]['num'] = $num;
$_SESSION['num'] = $num + 1;

$script = '<script language="javascript">
var div = parent.document.getElementById("div");
if(div == null){
div = parent.document.createElement("div");
div.id = "div";
parent.document.getElementById("form").appendChild(div);
}
if(parent.document.getElementById("div" + '.$num.') == null){
var child_div = parent.document.createElement("div");
child_div.id = "div" + '.$num.';
}

var img = parent.document.createElement("img");
img.src = "'.$imgpath.'";
img.height = 100;

if(parent.document.getElementById("a" + '.$num.') == null){
var a = parent.document.createElement("a");
a.style.cursor = "pointer";
a.id = "a" + '.$num.';
a.innerHTML = "删除";
}

child_div.appendChild(img);
child_div.appendChild(a);
div.appendChild(child_div);
</script>';
echo $script;
foreach($_SESSION['img'] as $k => $v){
$event = '<script>
var a = parent.document.getElementById("a" + '.$v['num'].');
if(parent.document.addEventListener){
a.addEventListener("click", function(){del('.$v['num'].')}, false);
}else if(attachEvent){
a.attachEvent("onclick", new Function("del("+'.$v['num'].'+")"));
}
</script>';
echo $event;
$j++;
}
}

function k_sort($arr){
$arr1 = $arr;
$arr = array();
$i = 0;
foreach($arr1 as $v){
$arr[$i] = $v;
$i++;
}
return $arr;
}
//================================================================test=================================================================
$tpl = new Tpl();
if(!isset($_SESSION))session_start();
$num = isset($_SESSION['num'])? $_SESSION['num']: 0;

$sub_type = '';
if(isset($_POST['submit_upload']))$sub_type = 'upload';
if(isset($_POST['submit_delete']))$sub_type = 'delete';
if($sub_type){
$num = isset($_POST['num'])? $_POST['num']: $num;//$_POST['num']为删除的图片数组num,后者的num为上传的图片数组num
$data = array('sub_type' => $sub_type,
'file' => $_FILES['file'],
'img_dir' => 'upload_img',
'num' => $num);
$return_data = upload($data);
}else{
$return_data = isset($_SESSION['img'])? $_SESSION['img']: '';
}
$return_data = k_sort($return_data);//支持FF

$tpl->assign('return_data', $return_data);
$tpl->display('task/a.html');
?>
回复
Dleno 2010-07-28
jquery-uplodify
下载下来直接用就可以了。
支持多文件或单文件上传。
效果很不错的
回复
amani11 2010-07-28

<!--form设置了 target='file_frame',实际上提交给了,隐藏的iframe,完成,服务器端,upload.php完成接收文件数据-->

<form action="upload.php" id="form1" name="form1" encType="multipart/form-data" method="post" target="file_frame">
<input name="filename" type="file">
</form>
<iframe name='file_frame' id="file_frame" style='display:none'></iframe>

回复
CunningBoy 2010-07-28
http://www.w3schools.com/php/php_ajax_php.asp
把这例子里面的文本框,换成你的文件上传的文本框就可以了。
回复
程序猿之殇 2010-07-28
ajaxupload
回复
发动态
发帖子
基础编程
创建于2007-09-28

2.1w+

社区成员

从PHP安装配置,PHP入门,PHP基础到PHP应用
申请成为版主
社区公告
暂无公告