<input type="file" name="image[0]" id="doc" οnchange="javascript:setImagePreview();">
<div class="page_one_imgin" id="localImag">
<img id="preview" src="images/two_page.jpg" width="100%" style="display: block;">
</div>
<script >
function setImagePreview(avalue) {
var docObj=document.getElementById("doc");
var imgObjPreview=document.getElementById("preview");
if(docObj.files &&docObj.files[0]){
//火狐下,直接设img属性
imgObjPreview.style.display = 'block';
imgObjPreview.style.width = '100%';
imgObjPreview.style.height = '5.2rem';
//imgObjPreview.src = docObj.files[0].getAsDataURL();
//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
console.log(imgObjPreview);
}else{
//IE下,使用滤镜
docObj.select();
var imgSrc = document.selection.createRange().text;
var localImagId = document.getElementById("localImag");
//必须设置初始大小
localImagId.style.width = "100%";
localImagId.style.height = "5.2rem";
//图片异常的捕捉,防止用户修改后缀来伪造图片
try{
localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
}
catch(e){
alert("您上传的图片格式不正确,请重新选择!");
return false;
}
imgObjPreview.style.display = 'none';
document.selection.empty();
}
return true;
}
</script>
-----------------------图片上传预览
以下为无刷新上传
html 页面
<div class="page_one_img"> <input type="file" id="doca" οnchange="addimg('doca','previewa','n_img2')"> <input type="hidden" name="n_img2" value="" id="n_img2"/> <div class="page_one_imgin" id="localImaga" > <img id="previewa" src="static/images/two_page.jpg" width="100%" style="display: block;"> <p></p> </div> </div>
function addimg(file,img,n_img){ var formData = new FormData($('form')[0]); formData.append('file',$("#"+file)[0].files[0]); //坑点: 无论怎么传数据,console.log(formData)都会显示为空,但其实值是存在的,f12查看Net tab可以看到数据被上传了 $.ajax({ url:'index.php?s=/api/upload', type: 'POST', data: formData, //这两个设置项必填 contentType: false, processData: false, success:function(data){ var srcPath = data; $('#'+img).attr('src',srcPath).css('height','5.2rem'); $("#"+n_img).val(data); } }) }
后台代码
//图片上传 public function upload_action(){ $upFile = $_FILES['file']; if ($upFile['error']==0 && !empty($upFile)) { $filename = date("YmdHis").$_FILES['file']['name']; $queryPath = 'static/uploads/img/'.$filename; //move_uploaded_file将浏览器缓存file转移到服务器文件夹 if(move_uploaded_file($_FILES['file']['tmp_name'],$queryPath)){ echo $queryPath; }else{ echo 1; } } }