`

轻松实现图片上传并回显

阅读更多
  图片上传及文件上传,前端html实现文件上传和普通的向后台传参数不同,必须用到form表单,同时form标签必须加上enctype="multipart/form-data"属性,method必须为post,表单中的input的type为file,这样前端上传文件的工作就完成了,这里后台文件的存储不做详细的介绍,因为用到的是struts2,文件上传的功能已经封装好了,但是还是需要注意几点,action中类型为File的属性名必须和input标签的name相同,同时action中必须有contentType和fileName属性,这里不是本文讲的重点就不做详细介绍了。
  大家知道,form表单的post请求是同步请求,如果没有指定target属性,默认情况下提交后会刷新页面,想要做到提交请求后不页面不动即能回显上传的图片,这就需要一些处理,这里我用到了隐藏的iframe,将form表单的target指向iframe的名字,这样form表单提交后返回的结果将在iframe中显示。

  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Image Demo</title>
<script type="text/javascript" src="js\jquery-1.7.1.min.js"></script>
<script type="text/javascript">
   function upload(){
	   $('form').submit();
	   $('img').attr('src','img/vote_img_loading.png')
   }
   $(document).ready(function(){
	   $(':input[type=file]').change(upload);
   });
   
   function showPic(path){
	   $('img').attr('src','file/'+path).next('span').css('visibility','visible');
	   
   }

</script>
<style type="text/css">
.pic {
	position: relative;
	width: 100px;
	height: 100px;
	float: left;
	display: inline;
	margin: 0 5px 0 0;
	cursor: pointer;
	overflow: hidden;
}

.pic span {
	position: relative;
	color: white;
	margin: -20px 0 0;
	display: block;
	height: 20px;
	width: 100px;
	text-align: center;
	overflow: hidden;
	line-height: 20px;
    background: url(img/template_list_titlebg.png) ;
} 

.pic form {
	position: absolute;
	width: 100px;
	height: 100px;
	overflow: hidden;
	z-index: 10;
	margin: -100px 0 0;
}

.pic input {
	font-size: 100px;
	cursor: pointer;
	-moz-opacity: 0;
	filter: alpha(opacity = 0);
	opacity: 0;
	background: none;
	border: none;
	margin: -10px 0 0 -650px 9;
}
</style>
</head>
<body>
    <iframe style="display:none" name="if">
    
    </iframe>
	<div class="pic">
		<img height="100" width="100" src="img/update_pic.png"><span
			style="visibility: hidden">重新上传</span>
		<form enctype="multipart/form-data" method="POST" action="upload.action" target="if">
			<input type="file" name="upload"/>
		</form>
	</div>
</body>
</html>



关于iframe中显示的内容是图片回显的关键,以下是返回的内容:
<html>
<head>
</head>
<body>
 <script type="text/javascript">
 var pid = window.location.search.split('=')[1];
 top.window.showPic(pid);
 
 </script>
</body>
</html>


  可以看到返回的内容很简单,就是一段javascript代码,因为当form表单提交后,我做了url重定向,并把图片的存储路径作为重定向url的参数,这段javascript代码首先从iframe的location中获得图片的存储路径,然后调用父窗口的showPic函数,并将图片存储路径传入函数,showPic函数是写在父床口中的,为什么可以这么做,因为子窗口可以调用父窗口的函数,但是反过来父窗口调用子窗口的函数是不被允许的。showPic函数如下:

function showPic(path){
	   $('img').attr('src','file/'+path).next('span').css('visibility','visible');
	   
   }

   它的作用就是将img标签的src指向传过来的图片路径,这时候浏览器就回去加载这个图片,这样就轻松的实现了图片上传并迅速回显的功能,我附上了实现这个功能的整个工程,是一个eclipse的maven工程,需要通过本机maven命令下载依赖包。
分享到:
评论
2 楼 青橙--杰 2015-12-01  
我是沙发,第一次做,不见怪
1 楼 青橙--杰 2015-12-01  

相关推荐

Global site tag (gtag.js) - Google Analytics