开始之前先说两句无关的,其实在ajax出现之前,web应用也可以是无刷新的,那时大多通过IFrame来做到这一点。当然Ajax出现之后,人们一窝蜂地投奔Ajax 的阵营了,iFrame 就乏人问津了。但是用iFrame来实现无刷新上传文件确实一个很好的选择。
ps:Ajax技术基本上可以说是由google公司带起来的,但少Gmail中上传文件用的还是 IFrame,所以使用IFrame来上传文件是最好的选择。
我在这里这里用的技术是jsp,其实asp,php等也是一样可以这么实现的
html:
<html>
<body>
<form action="/FileUploadServlet" 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" style=‘display:none‘></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>
java 逻辑处理:
package com.partner.servlets;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.partner.core.util.UploadConfigurationRead;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected final transient Log log = LogFactory.getLog(FileUploadServlet.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response){
//文件存放的目录
//File tempDirPath =new File(request.getSession().getServletContext().getRealPath("/")+File.separator+"uploads");
String path = UploadConfigurationRead.getInstance().getConfigItem("tempPath").trim();
File tempDirPath = new File(path);
if(!tempDirPath.exists()){
tempDirPath.mkdirs();
}
//创建磁盘文件工厂
DiskFileItemFactory fac = new DiskFileItemFactory();
//创建servlet文件上传组件
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("UTF-8");
//文件列表
List fileList = null;
//解析request从而得到前台传过来的文件
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException ex) {
ex.printStackTrace();
return;
}
//保存后的文件名
String imageName = null;
//便利从前台得到的文件列表
Iterator<FileItem> it = fileList.iterator();
while(it.hasNext()){
FileItem item = it.next();
//如果不是普通表单域,当做文件域来处理
BufferedInputStream in = null;
BufferedOutputStream out = null;
if(!item.isFormField()){
imageName = new Date().getTime()+"_"+item.getName();
try {
in = new BufferedInputStream(item.getInputStream());
out = new BufferedOutputStream(
new FileOutputStream(new File(tempDirPath+File.separator+imageName)));
Streams.copy(in, out, true);
} catch (IOException e) {
log.error("文件上传异常:", e);
}finally{
if(in != null){
try {
in.close();
} catch (IOException e) {
log.error("上传文件关闭输入失败",e);
}
}
if(out != null){
try {
out.close();
} catch (IOException e) {
log.error("上传文件关闭输出失败",e);
}
}
}
}
}
PrintWriter out = null;
try {
out = encodehead(request, response);
} catch (IOException e) {
e.printStackTrace();
}
//这个地方不能少,否则前台得不到上传的结果
out.write("<script>parent.callback(‘upload file success‘)</script>);
out.write(imageName);
out.close();
}
/**
* Ajax辅助方法 获取 PrintWriter
* @return
* @throws IOException
* @throws IOException
* request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
*/
private PrintWriter encodehead(HttpServletRequest request,HttpServletResponse response) throws IOException{
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
return response.getWriter();
}
}
原文地址:http://blog.csdn.net/lvyuanj/article/details/45818687