首先说下需要的文件
1. jQuery v1.10.2
2.ajaxfileUpload.js
然后就没了
思路
在每个iFrame中建立一个特征码 用一串随机数表示
然后在点击iFrame的时候遍历父页面中的iFrame 然后找出当前特征码和遍历特征码相等的那个iFrame
这样就得到了一个 htmObject 对象了 然后就可以调用父页面对象的函数将这个对象传进去对其进行操作了
将这段代码写出来 是因为没有具体的思路走了很多的弯路 现在经过几天的调试 已经可以跑起来了 不容易啊
下面是代码
1 uploadDemo.html 这个是测试页面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
body {
margin:0px;
padding:0px;
}
</style>
</head>
<script src="../admin_magent/LOAD/SCRIPT/jq.js"></script>
<script src="../admin_magent/LOAD/SCRIPT/ajaxfileupload.js"></script>
<body>
<form id="form1" name="form1" method="post" action="">
<input type="button" id="ad" value="添加" />
<div id="cont">
<div>
<iframe name="uploadFrame" title="0" src="imgUploads.jsp" height="180" width="580" frameborder="0"></iframe>
<input type="text" name="imgSrc" id="imgSrc"/>
<input type="text" name="imgText" id="imgText" />
</div>
</div>
</form>
</body>
</html>
<script>
for(i=1;i<10;i++){
$("#f"+i).hide();
}
function getPosition(target,src,text) {
$(target).parent().children("#imgSrc").val(src)
$(target).parent().children("#imgText").val(text)
}
function setSrc(target,src){
$(target).parent().children("#imgSrc").val(src)
}
function addFrame(target){
$(target).parent().after("<div style='display:none'>"+
"<iframe name='uploadFrame' title='0' src='imgUploads.jsp' height='180' width='580' frameborder='0'></iframe>"+
"<input type='text' name='imgSrc' id='imgSrc' />"+
"<input type='text' name='imgText' id='imgText' />"+
"</div>")
$(target).parent().next("div").slideDown(300)
}
function removeFrame(target){
$(target).parent().slideUp(300,function(){
$(target).parent().html("")
});
}
$(document).ready(function() {
$("#ad").click(function(){
for(i=0;i<10;i++){
if($("#f"+i).is(":visible")&&$("#f"+(i+1)).is(":hidden")){
$("#f"+(i+1)).show()
break;
}
}
})
var win=window.frames['uploadFrame'];
if(win.attachEvent){
win.attachEvent("onload", function(){
var text=win.document.getElementById("fileSrc").value
alert(text)
});
}else{
win.onload = function(){
$(win.document).find('#fileSrc').change(function () {
alert('change');
});
};
}
});
</script>
imgUpload.jsp 这是Iframe中的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/sellersOpt/imgUploads.jsp";
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="zh">
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
body {
margin:0px;
padding:0px;
}
#uploadFirst{
height:120px;
width:120px;
}
#addImg{
height:120px;
width:120px;
background-image:url(http://ww3.sinaimg.cn/mw690/7e4489e7gw1ejsntjwly3j202101wa9t.jpg);
background-position:center;
background-repeat:no-repeat;
background-color:#f4f4f4;
border-radius:10px;
-moz-border-radius:10px;
cursor:pointer;
}
#imgText{
float:right;
height:90px;
width:380px;
padding:0px;
margin:0px;
margin-top:5px;
margin-right:5px;
padding-top:10px;
padding-left:10px;
font-size:12px;
color:#999999;
text-align:left;
}
.uploadEnd{
width:550px;
height:150px;
display:none;
-moz-box-shadow:3px 3px 8px #808080;
-webkit-box-shadow:3px 3px 8px #808080;
box-shadow:2px 2px 5px #808080;
}
#imgShow{
height:140px;
width:140px;
float:left;
border:1px solid #69F;
margin-top:4px;
margin-left:6px;
background-color:#FFF;
}
#imgShow img{
max-height:140px;
max-width:140px;
}
#addImgTime{
display:none;
height:120px;
width:120px;
font-size:12px;
}
#addImgTime img{
max-height:100px;
max-width:100px;
margin-top:10px;
margin-left:10px;
}
#imgOption{
font-family:"微软雅黑";
font-size:14px;
padding-left:10px;
padding-top:5px;
}
#imgOption span{
font-weight: bold;
cursor:pointer;
padding-left:10px;
}
#falseImg{
padding-top:10px;
padding-left:10px;
padding-right:10px;
float:left;
}
#falseText{
padding-top:10px;
padding-bottom:10px;
font-family:"微软雅黑";
font-size:24px;
}
#falsOpting{
font-family:"微软雅黑";
font-size:14px;
color:#333333;
cursor:pointer;
display:block;
}
</style>
</head>
<script src="../admin_magent/LOAD/SCRIPT/jq.js"></script>
<script src="../admin_magent/LOAD/SCRIPT/ajaxfileupload.js"></script>
<body>
<div id="uploadFirst">
<div id="addImgTime"><img src="http://ww4.sinaimg.cn/mw690/7e4489e7gw1ejnxs8l5n9g20ci08cjzh.gif" />
请稍等,图片正在上传
</div>
<div id="addImg" οnclick="loads()">
</div>
</div>
<div id="uploadFalse" class="uploadEnd" style="background-color:#EFEFEF;">
<div id="falseImg">
<img src="http://ww2.sinaimg.cn/mw690/7e4489e7gw1ejpuxtlzajg203k03kgn8.gif" />
</div>
<div id="falseText">
抱歉上传失败,因为你的图片太大啦
</div>
<div id="falsOpting" onClick="loads()">
重新上传
</div>
</div>
<div id="uploadTrue" class="uploadEnd">
<div id="imgShow">
<img src="" />
</div>
<textarea id="imgText" name="imgText">图片描述(最多30个字)</textarea>
<div id="imgOption">
<input name="first" type="radio" value="" checked /><label for="first">设为首图</label>
<input name="fileSrc" id="fileSrc" type="hidden" value="" />
<span id="removes">删除</span>
</div>
</div>
<div id="fileTemp"><input name='fff' id='fff' type='file' title='' style='visibility:hidden;'></div>
</body>
</html>
<script>
var fileSrc=""
var imgArr = ["bmp","jpg","gif","png","psd","iso"]
function loads(){
document.getElementById("fff").click();
}
var identity =Math.floor( Math.random()*1000);
$(document).ready(function() {
$("#imgText").focus(function(){
if($(this).val()=="图片描述(最多30个字)"){
$(this).val("")
$(this).css("color","#000");
}
})
$('#imgText').blur(function(){
var parentWindow = window.parent;
for (var index = 0; index < parentWindow.frames.length; index++) {
if (identity == parentWindow.frames[index].identity) {
var pos = parentWindow.getPosition(parentWindow.frames[index].frameElement,fileSrc,$("#imgText").val());
break;
} else{continue}
}
})
$('body').on('change', '#fff', function(e){
if($(this).val().length>0){
var file = $(this).val();
var len = file.length;
var ext = file.substring(len-3,len).toLowerCase();
if($.inArray(ext,imgArr) == -1){
alert("请选择正确的文件")
return
}
else{
$("#addImg").hide()
$(".uploadEnd").hide()
$("#addImgTime").show()
$.ajaxFileUpload ({
url :'../imgUpload',
secureuri :false,
fileElementId :'fff',
dataType : 'json',
success : function (data, status){
$("#addImgTime").hide()
$("#uploadFirst").hide()
src=data.msg
if(src=="fileOutSize"){
$("#falseText").text("抱歉,你上传的文件太大了T_T")
$("#uploadFalse").fadeIn(300)
$("#fileSrc").val()
}else if(src=="notFileLength"){
$("#falseText").text("抱歉,你上传的是一个空文件")
$("#uploadFalse").fadeIn(300)
$("#fileSrc").val()
}else{
$("#uploadTrue").fadeIn(300)
$("#imgShow>img").attr("src","../"+src)
fileSrc=src
$("#fileSrc").val(src)
var parentWindow = window.parent;
for (var index = 0; index < parentWindow.frames.length; index++) {
if (identity == parentWindow.frames[index].identity) {
parentWindow.addFrame(parentWindow.frames[index].frameElement);
parentWindow.setSrc(parentWindow.frames[index].frameElement,src);
break;
}else{continue}
}
}
},
error: function (data, status, e) {
alert(e);
}
})
}
}
})
$("#removes").click(function(){
remove()
})
});
function remove(){
src=$("#fileSrc").val()
$.ajax({
type:"get",//请求方式
url:"../imgUpload",//发送请求地址
data:{//发送给数据库的数据
option:"remove",
src:src
},
//请求成功后的回调函数有两个参数
success: function(data,textStatus) {
if(data=="true"){
var parentWindow = window.parent;
for (var index = 0; index < parentWindow.frames.length; index++) {
if (identity == parentWindow.frames[index].identity) {
var pos = parentWindow.removeFrame(parentWindow.frames[index].frameElement);
break;
} else{continue}
}
}
}
});
}
</script>
后面的上传页面 imgUpload.java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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 databaseLink.Config;
public class imgUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
public imgUpload() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(request.getParameter("option"));
if (request.getParameter("option").equals("remove")) {
String src = request.getParameter("src");
src = this.getServletConfig().getServletContext().getRealPath("/")
+ src;
src=src.replace("/", "\\");
System.out.println(src);
File rFile = new File(src);
PrintWriter out = response.getWriter();
if (rFile.delete())
out.print("true");
else
out.print("false");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final long MAX_SIZE = 300 * 1024 * 1024;// 设置上传文件最大为 3M
// 允许上传的文件格式的列表
final String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "png",
"bmp", "psd" };
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
dfif.setRepository(new File(this.getServletConfig().getServletContext()
.getRealPath("/")
+ Config.imgTempFoder));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
// 设置最大上传尺寸
sfu.setSizeMax(MAX_SIZE);
PrintWriter out = response.getWriter();
// 从request得到 所有 上传域的列表
List fileList = null;
try {
fileList = sfu.parseRequest(request);
} catch (FileUploadException e) {// 处理文件尺寸过大异常
e.printStackTrace();
}
// 没有文件上传
if (fileList == null || fileList.size() == 0) {
out.print("{\"msg\":\"notFile\"}");
return;
}
// 得到所有上传的文件
Iterator fileItr = fileList.iterator();
int i = 0;
// 循环处理所有文件
while (fileItr.hasNext()) {
FileItem fileItem = null;
String path = null;
long size = 0;
// 得到当前文件
fileItem = (FileItem) fileItr.next();
i++;
// 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
if (fileItem == null || fileItem.isFormField()) {
continue;
}
// 得到文件的完整路径
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
if (size > 10*1024*1024) {
out.print("{\"msg\":\"fileOutSize\"}");
return;
}
if ("".equals(path) || size == 0) {
out.print("{\"msg\":\"notFileLength\"}");
return;
}
// 得到去除路径的文件名
String t_name = path.substring(path.lastIndexOf("\\") + 1);
// 得到文件的扩展名(无扩展名时将得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
// 拒绝接受规定文件格式之外的文件类型
int allowFlag = 0;
int allowedExtCount = allowedExt.length;
for (; allowFlag < allowedExtCount; allowFlag++) {
if (allowedExt[allowFlag].equals(t_ext))
break;
}
if (allowFlag == allowedExtCount) {
out.print("{\"msg\":\"filetypeError\"}");
return;
}
long now = System.currentTimeMillis();
// 根据系统时间生成上传后保存的文件名
String prefix = String.valueOf(now);
// 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下
String u_name = this.getServletConfig().getServletContext()
.getRealPath("/")
+ Config.imgFoder + prefix + "." + t_ext;
System.out.println(u_name);
try {
// 保存文件
fileItem.write(new File(u_name));
out.print("{\"msg\":\"" + Config.imgFoder + prefix + "."
+ t_ext + "\"}");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}