Home  >  Article  >  php教程  >  ajax图片上传方法(转载)

ajax图片上传方法(转载)

WBOY
WBOYOriginal
2016-06-07 11:44:241371browse

官方文档只是常规上传的例子。ajax上传网上的资料多有
错误,现转载一个测试通过的代码,以供大家参考。
参考网址:http://borissun.iteye.com/blog/1151350
-----------------------------------------------------
由于ajax无法发送带有文件的post请求。因此为了打到ajax效果,需要借助iframe。

Html代码










ajax图片上传方法(转载)


form表单中action正常填写处理文件上传的操作。target填写一个隐藏的iframe。
这样表单提交之后,文件会被上传,但是页面却不会刷新,因为表单提交后被刷新页面为隐藏的iframe,因此用户看到的效果和ajax处理的效果是一样的。

现在看到的效果是和ajax一样了,但是ajax是有返回值的。但是现在我们值刷新了iframe页面,却没有ajax的返回值,不知道操作到底是成功了还是失败了。因此需要在页面中写一个js的callback方法,然后在处理上传操作成功后来调用这个callback方法。

这个例子是php做的文件处理,其他语言同理。
Php代码
public function uploadImg()
{
try{
if($_FILES["AidImg"]["size"]!=0)
{
$uploadPath = MB_ROOT_DIR . "/pic";
if ($_FILES["AidImg"]["size"] if ($_FILES["AidImg"]["error"] > 0) {
error($_FILES["AidImg"]["error"],"index.php/Campaign/campaignPublish");
} else {
$suffix = substr($_FILES["AidImg"]["name"], strrpos($_FILES["AidImg"]["name"], '.') + 1);
$imgDate=date("YmdHis");
$name = $imgDate . rand("1000", "9999") . "." . $suffix;
if (!is_dir($uploadPath)) {
mkdir($uploadPath);
}
if (move_uploaded_file($_FILES["AidImg"]["tmp_name"], $uploadPath . "/" . $name)) {
$pf = new IBPostFile(UPLOAD_IMAGE_URL,UPLOAD_IMAGE_PORT);
$pf->setFile("AidImg", $uploadPath . "/" . $name);
$pf->sendRequest();
$imgUrl = $pf->getResponse();
}
}
} else {
echo "<script>parent.callback('图片大小不能超过2M',false)</script>";
return;
}
}
}
catch(Exception $e)
{
echo "<script>parent.callback('图片上传失败',false)</script>";
return;
}
echo "<script>parent.callback('$imgUrl',true)</script>";
}


echo "<script>parent.callback('图片上传失败',false)</script>";
这句花,调用了iframe的父页面的callback方法。并且将一些信息作为参数传进了callback方法。


Javascript代码
function uploadImg()
{
var names=$("#AidImg").val().split(".");
if(names[1]!="gif"&&names[1]!="GIF"&&names[1]!="jpg"&&names[1]!="JPG"&&names[1]!="png"&&names[1]!="PNG")
{
$("#imgError").html("
"+"海报必须为gif,jpg,png格式");
$("#imgError").show();
return;
}
$("#formImg").submit();
}

function callback(message,success)
{
if(success==false)
{
$("#imgError").html("
"+message);
$("#imgError").show();
}
else{
$("#imgError").hide();
var paths=message.split("/");
$("#img").attr("src",message);
$("input[name='imgUrl']").val(paths[paths.length-1]);
}
}


这里是页面的callback方法,接受了上传图片处理后返回的结果。

这样,就用iframe模拟了ajax来上传文件。

AD:真正免费,域名+虚机+企业邮箱=0元

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn