js实现图片上传并正常显示
原文链接:https://www.jb51.net/article/76651.htm
js实现图片上传并正常显示
1.html代码部分
<form action='' method='post' name='myform'>
<input type='file' id='iptfileupload' onchange='show()' value='' />
<img src='1.jpg' alt='' id='img' />
</form>
1.javascript代码部分
<script type="text/javascript">
function getPath(obj,fileQuery,transImg) {
var imgSrc = '', imgArr = [], strSrc = '' ;
if(window.navigator.userAgent.indexOf("MSIE")>=1){ // IE浏览器判断
if(obj.select){
obj.select();
var path=document.selection.createRange().text;
alert(path) ;
obj.removeAttribute("src");
imgSrc = fileQuery.value ;
imgArr = imgSrc.split('.') ;
strSrc = imgArr[imgArr.length - 1].toLowerCase() ;
if(strSrc.localeCompare('jpg') === 0 || strSrc.localeCompare('jpeg') === 0 || strSrc.localeCompare('gif') === 0 || strSrc.localeCompare('png') === 0){
obj.setAttribute("src",transImg);
obj.style.filter=
"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path+"', sizingMethod='scale');"; // IE通过滤镜的方式实现图片显示
}else{
//try{
throw new Error('File type Error! please image file upload..');
//}catch(e){
// alert('name: ' + e.name + 'message: ' + e.message) ;
//}
}
}else{
// alert(fileQuery.value) ;
imgSrc = fileQuery.value ;
imgArr = imgSrc.split('.') ;
strSrc = imgArr[imgArr.length - 1].toLowerCase() ;
if(strSrc.localeCompare('jpg') === 0 || strSrc.localeCompare('jpeg') === 0 || strSrc.localeCompare('gif') === 0 || strSrc.localeCompare('png') === 0){
obj.src = fileQuery.value ;
}else{
//try{
throw new Error('File type Error! please image file upload..') ;
//}catch(e){
// alert('name: ' + e.name + 'message: ' + e.message) ;
//}
}
}
} else{
var file =fileQuery.files[0];
var reader = new FileReader();
reader.onload = function(e){
imgSrc = fileQuery.value ;
imgArr = imgSrc.split('.') ;
strSrc = imgArr[imgArr.length - 1].toLowerCase() ;
if(strSrc.localeCompare('jpg') === 0 || strSrc.localeCompare('jpeg') === 0 || strSrc.localeCompare('gif') === 0 || strSrc.localeCompare('png') === 0){
obj.setAttribute("src", e.target.result) ;
}else{
//try{
throw new Error('File type Error! please image file upload..') ;
//}catch(e){
// alert('name: ' + e.name + 'message: ' + e.message) ;
//}
}
// alert(e.target.result);
}
reader.readAsDataURL(file);
}
}
function show(){
//以下即为完整客户端路径
var file_img=document.getElementById("img"),
iptfileupload = document.getElementById('iptfileupload') ;
getPath(file_img,iptfileupload,file_img) ;
}
</script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?