`

用iframe模拟ajax上传文件

阅读更多

项目中同事使用AjaxFrom上传文件时后台保存成功,而前台确不进回调函数。自己也没去解决掉这个问题,后来同事介绍说用iframe模拟Ajax,自己从网上也看到了一些iframe做伪Ajax上传的,感觉也算是一个小技巧,故而在此记录一下。
网上说,直接用$.post在上传文本信息没有问题,但是直接上传图片就不行了。当然其实这个我们也可以使用封装好的flash方法,但是封装好的东西灵活性差,而且也不见得都会对flash进行修改。所以iframe模拟就是一个比较不错的选择。
iframeAjax.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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=UTF-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript" src="./res/js/jquery-1.8.2.js">
	
</script>
<title>Iframe 模拟AJax提交</title>
<script type="text/javascript">
	function uploadImg() {
		var names = $("#imageId").val().split(".");
		if (names[1] != "gif" && names[1] != "GIF" && names[1] != "jpg"
				&& names[1] != "JPG" && names[1] != "png" && names[1] != "PNG") {
			$("#errorTip").html("海报必须为gif,jpg,png格式");
			$("#errorTip").show();
			return;
		}
		$("#formId").submit();
	}

	function callback(success, message, url) {
		if (success == false) {
			$("#errorTip").html(message);
			$("#errorTip").show();
		} else {
			$("#errorTip").hide();
			$("#successTip").html(message);
			$("#successTip").show();
			$("#img").attr("src", "uploads/" + url);
			$("#img").show();
		}
	}
</script>
</head>
<body>

	<form id="formId" action="IframeAjax" method="post"
		target="hiddenFrameName" enctype="multipart/form-data">
		<div>
			<label>附件:</label> <input id="imageId" type="file" name="imageName"
				onchange="uploadImg()" />
			<div style="display: none; color: red;" id="errorTip">活动海报不可为空
			</div>
			<div style="display: none; color: green;" id="successTip"></div>
		</div>
	</form>
	<iframe style="display: none" name='hiddenFrameName' id="hidden_frame"></iframe>

	<img id="img" src="" width="80" height="80" style="display: none;" />


</body>
</html>

说明:
form表单中action正常填写处理文件上传的操作。target填写一个隐藏的iframe的name。这样表单提交之后,文件会被上传,但是页面却不会刷新,因为表单提交后被刷新页面为隐藏的iframe,因此用户看到的效果和ajax处理的效果是一样的。
同时我们知道Ajax另一个就是回调处理,那么我们这里也可以定义几个需要回调处理的JS方法,然后在后台调用。

IframeAjax.java(这里我直接采用的Servlet处理,原理都是一样的)

package com.iflytek.demo;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class IframeAjax
 */
public class IframeAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public IframeAjax() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 这里是取得WebContent的根目录路径
		String realPath = request.getSession().getServletContext().getRealPath("/");
		// 这里是为了方便管理上传的文件,因而在根目录下建立一个文件夹
		File uploadPath = new File(realPath, "uploads");
		uploadPath.mkdirs();
		// 解决Servelt to js乱码问题
		response.setContentType("text/html;charset=UTF-8");
		// 判断是否是带有附件的上传
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			ArrayList<String> pics = new ArrayList<String>();
			try {
				@SuppressWarnings("unchecked")
				List<FileItem> items = upload.parseRequest(request);
				for (FileItem f : items) {
					if (f.isFormField()) {// 说明是表单项
					} else {// 说明是文件
						String srcName = f.getName();// 取得上传时的文件名
						srcName = srcName.toLowerCase();// 统一将文件名改为小写
						String extName = "";// 扩展名
						int pos = srcName.lastIndexOf('.');
						// 因为有的文件上传它可能没有扩展名,所以这里注意要进行一步判断,判断后再取得.扩展名
						if (pos != -1) {
							extName = srcName.substring(pos);
						}
						// 取得当前时间的纳秒数加扩展名来做保存文件的文件名
						String name = System.nanoTime() + extName;
						File file = new File(uploadPath, name);
						f.write(file);// 保存到指定的目录中去
						pics.add(name);

					}
				}
			} catch (Exception e) {
				response.getWriter().write("<script>parent.callback(false,'图片上传失败','')</script>");
			}

			response.getWriter().write("<script>parent.callback(true,'图片上传成功','" + pics.get(0) + "')</script>");
			// 一般如果是直接表单提交的方法需要返回
			// request.getRequestDispatcher("iframeAjax.jsp").forward(request,
			// response);

		}
	}

}

小感:找找总会有方法的。

 

分享到:
评论
1 楼 winner_king 2013-10-22  
不错。

相关推荐

    PHP+iframe模拟Ajax上传文件功能示例

    答案:可以使用iframe模拟Ajax上传文件。接下来博主将使用iframe来模拟Ajax来上传文件。 首先看一下效果图: 文件结构图: 09-iframe-upload.html文件: 页面中有一个表单,表单中有一个上传文件按钮和提交按钮,...

    JSP_模拟AJAX实现无刷新文件上传

    AJAX无法实现文件上传功能,原因是JavaScript安全限制不能对文件执行操作,但是通过IFRAME框架可以模拟实现无刷新效果。虽说是无刷新的,但状态栏会刷新一下。代码是一个JSP的示例。

    js动态创建上传表单通过iframe模拟Ajax实现无刷新

    { //创建iframe var iframe = document.createElement(“iframe”); document.body.appendChild(iframe); iframe.id = ‘iframeName’; iframe.name = ‘iframeName’; iframe.style.display = ‘none’; //创建form...

    基于HTML5的可预览多图片Ajax上传

    我之前曾翻译编辑过一篇“Ajax Upload多文件上传插件”的文章,此插件的亮点是使用隐藏的iframe框架页面模拟ajax上传,但是,实际上,还是一次只能上传1张图片,可以多次上传而已。 HTML5是个好东东,其中之一就是...

    仿iframe效果Aajx文件上传实例

    前段时间在解决ajax上传文件时折腾了好一阵。直接用$.post上传文本信息肯定是没有问题的。但是$.post直接上传图片是不可行的。 后来看到网上的一些解决方案,有现成的ajax上传文件的封装的方法也有利用flash的。...

    WebIM_Ajax框架

    7.ajax上传图片 8.裁切图片 9.js表单验证 10.悬浮层拖拽 11.列表节点拖拽排序 12.列表节点拖拽移动 13.Fixed 效果(固定居上/中/下、左/中/右),兼容 IE6 14.base64 编码 15.网站风格切换 16.js插件:模拟 Confirm ...

    ExtAspNet_v2.3.2_dll

    -修正了使用IFrameUrl的Tab在切换过程中会重复加载的问题,这是一个在v2.1.6引入的问题(feedback:eroach)。 -修正了启用AutoPostBack的Grid,其RowClick会覆盖LinkButtonField, HyperLinkField, CheckBoxField的...

    ExtAspNet v2.2.1 (2009-4-1) 值得一看

    -修正了使用IFrameUrl的Tab在切换过程中会重复加载的问题,这是一个在v2.1.6引入的问题(feedback:eroach)。 -修正了启用AutoPostBack的Grid,其RowClick会覆盖LinkButtonField, HyperLinkField, CheckBoxField的...

    超实用的jQuery代码段

    8.11 使用AJAX刷新上传图片 8.12 使用AJAX刷新验证PHP会话是否有效 8.13 在AJAX异步调用时显示加载指示器 8.14 在AJAX异步调用时处理JSON数据 8.15 解析XML数据并加载到HTML表格 8.16 jQuery AJAX错误的处理方法 ...

    jsmodule:JS组件

    jsmoduleJS组件########轮播图片、支持手机滑动#仿ajax上传文件iframe#点击的进度条#文本框计数统计#图片的懒加载#本地缓存localStorage#pc地区联动选择area#图片放大镜#ajax分页插件paging#url参数和表单json参数#...

    python入门到高级全栈工程师培训 第3期 附课件代码

    04 Form组件上传文件 05 上传相关内容梳理 06 Model操作知识提问 07 Model操作概述 08 Model字段 09 Model连表字段参数详解 10 Model自定义多对多第三张表 11 强插一道面试题 12 Model连表操作梳理 13 多对多自关联 ...

Global site tag (gtag.js) - Google Analytics