之前我写图片上传可能就是在图片上传的时候把提交事件委托给一个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