使用ajax,结合jquery,php实现图片上传预览功能

大致逻辑:点击页面的file,上传图片到指定的php处理图片的文件,处理完成以后,将图片的连接地址返回,JS控制返回的数据,然后将图片动态的展示出来
html代码
<label>
<img class="fileimg" height="200px;" src=""/>
<input type="file" style="display: none;" >
</label>

js代码
$(document).ready(function() {
var url = "fileupload.php";    //这里是你需要那个文件来处理图片
$("#file").change(function() {
//普通上传
var upload = function(f) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
var formData;
formData = new FormData();
formData.append('file', f);
xhr.onreadystatechange = function(response) {
if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
$(".fileimg").attr("src","{:C('PUBLIC')}/"+(xhr.responseText));
$("#file").remove();
$("#nowPic").val(xhr.responseText);
} else if (xhr.status != 200 && xhr.responseText) {
}
};
xhr.send(formData);
};
if ($("#file")[0].files.length > 0) {
upload($("#file")[0].files[0]);
} else {
console && console.log("form input error");
}
})
});

php代码 使用的是thinkphp3.2.3来处理的
public function index($type='upload')
{
$upload = new ThinkUpload();// 实例化上传类
$upload->rootPath = './Public/Uploads/'.$type.'/'; // 设置附件上传根目录
$upload->autoSub = false;
$info = $upload->upload();
if (!$info){
$this->error($upload->getError());
}else{
//echo json_encode('/Uploads/'.$type.'/'.$info['savepath'].$info['savepath']);
echo '/Uploads/'.$type.'/'.$info["file"]['savepath'].$info["file"]['savename'];
}
}