上传图片后将图片显示在当前页面上,本打算用ajax,但是上传图片必须设置 enctype="multipart/form-data",而要提交之后页面不跳转,所以查资料后采用form+iframe的方式。空的iframe并且不显示,将form的target设置为iframe,就会提交到iframe上,从而实现不刷新页面上传。
<form name="uploadForm" id="uploadForm" method="post" enctype="multipart/form-data"
action="/cars/api/v1/template/createTemplate" target="uploadFrame">
<p style="margin:10px 0;">上传图片:
<input type="file" name="imageFile" ID="fupPhoto"/>
<input type="text" name="brand" ID="brand" />
<input type="submit" id="fileSubmit" name="Submit" value="上传" />
<iframe name="uploadFrame" id="uploadFrame" style="display:none;"></iframe>
</p>
</form>
<img id="imgPhoto" src="" width="300">
js:
$("#fileSubmit").click(function(){
if($.browser.msie){
window.uploadForm.submit();
}else{
$("#uploadForm").submit();
}
});
function uploadFile(msg){
if(msg!=error){
$("#imgPhoto").attr("src",msg);
}else {
alert("上传图片失败!");
}
后台上传成功,在iframe页面调用父页面方法设置图片路径
PrintWriter out = response.getWriter();
filePathName =serverFile.getName();
out.println("<script>window.parent.uploadFile('" + filePathName + "')</script>");
参考资料:http://perfectlife.iteye.com/blog/396959