iframe 上传
upload.htmlhtml>
Titlevar lastFileName;
$("#fileipt").change(function() {
var fileName = $(this).val();
var pos = fileName.lastIndexOf("\\");
fileName = fileName.substr(pos+1, fileName.length); // 截取出文件名 因为会带路径
lastFileName = fileName;
$("#submit").click();
});
function stopSend($url) {
$("#tag_img").attr("src",$url);
}
upload.php<?php
/**
* Created by PhpStorm.
* User: chenxiaolong
* Date: 7/21/17
* Time: 10:24
*/
//var_dump($_FILES);
$file=$_FILES['userfile'];
if($file['size'] != 0) {
$name=rand(0,500000).dechex(rand(0,10000)).".jpg";
move_uploaded_file($file['tmp_name'],$name);
if($name) {
echo "parent.stopSend('$name')";
}
}
ajax 无刷新上传图片修改头像
$("#J_headimg").click(function() {
$("#pic").click();
return false;
});
$("#pic").change(function() {
var $that = $(this);
var imgPath = $(this).val();
if (imgPath == "") {
alert("请选择上传图片!");
return;
}
//判断上传文件的后缀名
var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
if (strExtension != 'jpg' && strExtension != 'gif'
&& strExtension != 'png' && strExtension != 'bmp' && strExtension != 'jpeg') {
alert("请选择图片文件");
return;
}
var formData = new FormData();
formData.append('file', $that[0].files[0]);// php 用$_FILES['file']接收
console.log($that[0].files[0]);
$.ajax({
type: "POST",
url: "__URL__/uploadimg",
data: formData,
cache: false,
processData: false,// 需要加这两个参数
contentType: false,
success: function(data) {
var obj = JSON.parse(data);
if(obj.status == 0) {
$("#preimg").attr("src","Public/Upload/" + obj.data);
$("#headimg").val(obj.data);
} else {
alert(obj.data);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("上传失败,请检查网络后重试");
}
});
});
对应uploadimg方法public function uploadimg() {
$file = $_FILES['file'];
$arr = array('jpg'=>'p_w_picpath/jpeg','png'=>'p_w_picpath/png','gif'=>'p_w_picpath/gif','bmp'=>'p_w_picpath/bmp');
if($ext = array_search($file['type'],$arr)) {
$rand = uniqid();
$filename = "Public/Upload/avatar/{$rand}.{$ext}";
} else {
exit(json_encode(array('status'=>2,'data'=>'只支持图片上传')));
}
$r = move_uploaded_file($file['tmp_name'],$filename);
if($r) {
exit(json_encode(array('status'=>0,'data'=>"avatar/$rand.$ext")));
} else {
exit(json_encode(array('status'=>1,'data'=>'上传失败')));
}
}