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>