---
title: "iframe实现无刷新文件上传"
author: "voole"
date: "2013-08-15T14:31:35Z"
tags: []
categories: ["Web前端"]
slug: "iframe"
draft: false
lastmod: "2013-08-15T14:34:06Z"
id: 1924966
url: "https://voole.iteye.com/blog/1924966"
---

```
＜html＞        
＜body＞        
       
＜form action="upload.jsp" id="form1" name="form1" encType="multipart/form-data"   method="post" target="hidden_frame" ＞        
     ＜input type="file" id="file" name="file" style="width:450"＞        
     ＜INPUT type="submit" value="上传文件"＞＜span id="msg"＞＜/span＞        
     ＜br＞        
     ＜font color="red"＞支持JPG,JPEG,GIF,BMP,SWF,RMVB,RM,AVI文件的上传＜/font＞                      
     ＜iframe name='hidden_frame' id="hidden_frame" ＞＜/iframe＞        
＜/form＞        
       
＜/body＞        
＜/html＞        
       
＜script type="text/javascript"＞        
function callback(msg)        
{        
     document.getElementById("file").outerHTML = document.getElementById("file").outerHTML;        
     document.getElementById("msg").innerHTML = "＜font color=red＞"+msg+"＜/font＞";        
}        
＜/script＞
```

一共两个文件就可实现：index.html 和 upload.jsp.

在上传文件的时候要注意html的file标签也要给name赋值,否则post上去后,服务器端是找不懂file对象的. 

 

index.html 中主要要做的就是写一个 form 和 iframe ，并把 form 的 target 设为 iframe 的名字，注意要 把 iframe 设为不可见，其他的都是正常的文件上传的写法，这样刷新的页面就是这个隐藏的 Iframe ，而在 index.html 中是不会 有页面刷新的，js的 callback 方法是回调方法。用于清空文件上传框和显示后台信息，注意清空文件上传框的方法，和普通方法有点不一样。