利用iframe实现文件上传

现在文件上传都是通过Ajax实现。但是利用iframe也可以实现非常类似于Ajax文件上传的效果。

首先,上传文件的组件我使用的是apache的commons-fileupload和commons-io包

先给出利用commons-fileupload组件完成文件上传的后台代码
package com.gxa.edu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;

/**
 * 文件上传的Servlet,我们使用Apache组织提供的commons-fileupload.jar和commons-io.jar包实现文件上传功能
 * @author Administrator
 *
 */
public class FileUploadServlet_2 extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public FileUploadServlet_2() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		request.setCharacterEncoding("gb2312");
		response.setCharacterEncoding("gb2312");
		PrintWriter out = response.getWriter();
		
		final long maxSize = 1024 * 1024 * 5; //定义文件允许上传的大小
		final String[] fileExtType = {"jpg" , "JPG" , "gif", "doc" , "docx"}; //定义允许上传文件后缀名
		DiskFileItemFactory disk = new DiskFileItemFactory(); //设置实例化一个硬盘工厂
		disk.setSizeThreshold(5120); //设置上传文件时临时存放文件到内存缓存区的大小为5kb
		String tmpFile = this.getServletContext().getRealPath("/");
		System.out.println("临时上传文件路径:" + tmpFile);
		File file = new File(tmpFile + "\\" + "tmpFile"); //在javaweb下面建立一个tmpFile文件,该文件用于存放上传时候的临时文件夹
		if (!file.exists()) {
			file.mkdirs();
		}
		disk.setRepository(file); //设置缓存的路径或目录
		ServletFileUpload sfu = new ServletFileUpload(disk); //初始化上传文件的核心类ServletFileUpload
		sfu.setSizeMax(maxSize); //设置文件允许上传的大小
		List list = null; //List列表用于存储上传文件表单域中的所有上传值
		try {
			list = sfu.parseRequest(request); //解析请求过来的上传文件表单域,通过将域中的所有值放到List中
		} catch (FileUploadException e) {
			e.printStackTrace();
			if (e instanceof SizeLimitExceededException) {
				out.println("上传文件超过5M");
				out.println("<script language='javascript'>");
				out.println("window.parent.document.getElementById('msg').innerHTML='<font color=red>上传文件超过5M</font>';");
				out.println("window.parent.document.getElementById('file').outerHTML=window.parent.document.getElementById('file').outerHTML;");
				out.println("</script>");
				return;
			}
		}
		
		Iterator iterator = list.iterator();
		while (iterator.hasNext()) {
			FileItem fileItem = (FileItem) iterator.next();
			if (fileItem.isFormField()) { //判断是否是一个普遍的表单域,true则表示是普遍表单域而不是文件域
				String fieldName = fileItem.getFieldName();
				String value = fileItem.getString("gb2312");
			} else {
				String fileFieldName = fileItem.getFieldName(); //获取文件域的名称
				System.out.println("文件域的名称:" + fileFieldName);
				String fileName = fileItem.getName(); //上传文件的名称,包括全路径
				System.out.println("上传文件的名称:" + fileName);
				long fileSize = fileItem.getSize(); //上传文件的大小
				System.out.println("上传文件的大小:" + fileSize);
				
				file = new File(tmpFile + "\\" + "fileUploadDir");
				if (!file.exists()) {
					file.mkdirs();
				}
				
				String fileUploadName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
				FileOutputStream fos = new FileOutputStream(tmpFile + "\\" + "fileUploadDir" + "\\" + fileUploadName);
				
				if (fileItem.isInMemory()) { //判断上传的文件是否已经在内存中
					try {
						fos.write(fileItem.get());
						out.println("上传文件" + fileUploadName + "成功");
					} catch (IOException e) {
						out.println("上传文件失败");
						return;
					} finally {
						fos.close();
					}
					
				} else {
					InputStream is = fileItem.getInputStream(); //获取上传文件内容的输入流
					int i = 0;
					byte[] b = new byte[1024 * 4];
					try {
						while ((i = is.read(b)) != -1) {
							fos.write(b, 0, i);
						}
						out.println("上传文件:" + fileUploadName + "成功");
						out.println("<script language='javascript'>");
						out.println("window.parent.document.getElementById('msg').innerHTML='<font color=red>上传文件成功</font>';");
						out.println("window.parent.document.getElementById('file').outerHTML=window.parent.document.getElementById('file').outerHTML;");
						out.println("</script>");
					} catch (IOException e) {
						out.println("上传文件失败");
						out.println("<script language='javascript'>");
						out.println("window.parent.document.getElementById('msg').innerHTML='<font color=red>上传文件失败</font>';");
						out.println("window.parent.document.getElementById('file').outerHTML=window.parent.document.getElementById('file').outerHTML;");
						out.println("</script>");
					} finally {
						is.close();
						fos.close();
					}
				}
			}
		}
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occure
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}


下面的JSP页面代码
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!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=gb2312">
<title>文件上传-3</title>
</head>

<body>
<form name="form1" enctype="multipart/form-data" method="post" action="servlet/FileUploadServlet_2" target="hidden_iframe">
  <input type="file" name="file" id="file">
  <input type="submit" value="文件上传"><span id="msg"></span>
  <iframe name="hidden_iframe" id="hidden_iframe" style="display:none "></iframe>
</form>
</body>
</html>

你可能感兴趣的:(apache,html,Ajax,SQL Server,servlet)