html5无刷新上传,html5 轻松解决跨域无刷新上传图片

之前我写图片上传可能就是在图片上传的时候把提交事件委托给一个iframe去完成。然后在请求的地址里面处理完图片上传之后执行一段JS。

/**客户端代码**/

$(function() {

$('#fileUp').change(function() {

$('#form').submit();

});

})

function uploadImage(url){

$('#iconImageShow').attr('src',url).css({

'margin':'0 0 0 100px',

'width': '100px',

'height': '100px'

}).fadeIn();

}

//服务器端代码

$destination = '/path/test.jpg';

if(!move_uploaded_file($_FILES["upfile"]['tmp_name'],$destination)){

echo "";

exit;

}else{

$imgUrl = "http://xxx.com/".$filename;

echo "";

exit;

}

但是今天的情况略有不同的是要跨域请求,在A服务器请求B服务器,把上面的服务器端代码放在B服务器里,上传可以完成,但是下面的js代码则不能执行,而是作为文本输出返回。我想到既然只能返回,那么如果能在上传的时候监听到上传进度,上传完毕之后,拿到返回值,然后执行回调函数。这样不就OK啦。网上一搜,OK,解决了。代码如下:

/**客户端代码**/

function uploadFile() {

var fd = new FormData();

fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);

fd.append("ts", ts);//自定的表单内容

var xhr = new XMLHttpRequest();

xhr.upload.addEventListener("progress", uploadProgress, false);

xhr.addEventListener("load", uploadComplete, false);

xhr.addEventListener("error", uploadFailed, false);

xhr.open("POST", postUrl);//postUrl请求的地址

xhr.send(fd);

}

function uploadProgress(evt) {

if (evt.lengthComputable) {

var percentComplete = Math.round(evt.loaded * 100 / evt.total);

document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';

} else {

document.getElementById('progressNumber').innerHTML = 'unable to compute';

}

}

function uploadComplete(evt) {

var data = eval('(' + evt.target.responseText + ')');

var imageList = document.getElementById("imageList");

var img = document.createElement("img");

img.src = data.url;

imageList.appendChild(img);

}

function uploadFailed() {

alert("上传失败");

}

上传进度

//服务器端代码

header( 'Access-Control-Allow-Origin:http://xxx.com' );

$destination = '/path/test.jpg';

if(!move_uploaded_file($_FILES["upfile"]['tmp_name'],$destination)){

echo json_encode(array('info'=>'上传失败'));

exit;

}else{

$imgUrl = "http://xxx.com/test.jpg";

echo json_encode(array('url'=>$imgUrl));

exit;

}

html5 ajax 多图上传:http://www.tuicool.com/articles/F73i6r

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值