用iframe做不刷新批量上传
来源:互联网 发布:软件接口设计规范 编辑:程序博客网 时间:2024/05/01 09:29
因为拦截器使用的是struts2 如果使用需要struts2的7个架包
1.struts2-core-2.0.9.jar
2.xwork-2.0.4.jar
3.commons-fileupload-1.1.1.jar
4.commons-io-1.1.jar
5.commons-logging-1.0.4.jar
6.freemarker-2.3.8.jar
7.ognl-2.6.11.jar
第一个文件 EditPictureAction .java
第二个文件 struts.xml
第三个文件 web.xml
第四个文件 loadphoto.jsp
第五个文件 uploadfile.js
第六个文件 uploadfile.css
第七个文件 testupok.jsp
<%=request.getAttribute("returnValue")%>
效果
一共7个文件
在IE与firefox下测试通过
var cr = new CreateLoad('all','buttons',5,'EditPicture.action',list); 需要5个参数
第一个是 显示文件信息的div的id
第二个是显示按钮的div的id
第三个是一次做多上传多少个文件
第四个是文件上传的action
第五个是和文件一起需要传递的附加值 以数组的方式传递
var list = new Array();list.push({key:"c",value:"citie"});
key是前台赋值组件的id ,value是后台接收的name
诚求js达人帮我优化uploadfile.js,
声明 :大家互相学习 :) 转载请注明出处
1.struts2-core-2.0.9.jar
2.xwork-2.0.4.jar
3.commons-fileupload-1.1.1.jar
4.commons-io-1.1.jar
5.commons-logging-1.0.4.jar
6.freemarker-2.3.8.jar
7.ognl-2.6.11.jar
第一个文件 EditPictureAction .java
package com.struts;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import javax.imageio.ImageIO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* @author peng
*
*/
public class EditPictureAction extends ActionSupport {
private static final String[] PHOTOTYPE = {"bmp", "jpg", "jpeg", "gif","png", "ico", "jpe", "jfif" };
private static final String DEFAULTALBUM = "upfile/"; //存放图片的文件夹
private static final String LOGOPHOTO = "images/jxbq/1.gif"; //水印图片
private static final long serialVersionUID = 1L;
//照片与水印比例
private static final Integer PHOTOPROPORTION = 6;
private static final Log log = LogFactory.getLog(EditPictureAction.class);
private File myFile;
private String name;
private Long citie;
private Long categoryId;
private String returnValue;
private String recordedTime;
private String fileName;
private String contentType;
private String imageFileName;
/**
* 上传照片
*/
@Override
public String execute() {
try{
boolean isSuffix = true;
String suffix = getExtention(fileName).toLowerCase();
for (String string : PHOTOTYPE) {
if (("." + string).equals(suffix)) {
isSuffix = false;
}
}
if (isSuffix) {
returnValue = "UP_FILE_NO";
return SUCCESS;
}
String prefix = String.valueOf(new Date().getTime());
imageFileName = prefix + suffix;
String breviaryPath = prefix + "_s" + suffix;
String allpath = ServletActionContext.getServletContext().getRealPath("/") + DEFAULTALBUM;
createNewImage(myFile, allpath, imageFileName, breviaryPath);
String photoname = getCaption(fileName);
if(photoname.length() > 30) photoname = photoname.substring(0,30);
System.out.println("**********照片信息start***********");
System.out.println("photoname:" + photoname);
System.out.println("albumId:" + categoryId);
System.out.println("photodate:" + recordedTime);
System.out.println("cityId:" + citie);
System.out.println("photoBigPath:" + imageFileName);
System.out.println("photoSmallPath:" + breviaryPath);
System.out.println("**********照片信息end***********");
returnValue = "UP_FILE_OK";
return SUCCESS;
} catch (IOException e) {
log.error(e);
returnValue = "UP_FILE_NO";
return SUCCESS;
} catch (Exception e) {
log.error(e);
return ERROR;
}
}
/**
* 制作缩略图与水印图
* @param file
* @param allpath
* @param imageFileName
* @param breviaryPath
* @throws IOException
*/
public static void createNewImage(File file, String allpath,
String imageFileName, String breviaryPath) throws IOException {
Image image;
image = javax.imageio.ImageIO.read(file);
int wideth = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage tag = new BufferedImage(wideth, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.createGraphics();
g.drawImage(image, 0, 0, wideth, height, null); // ����ˮӡͼ
File logoFile = new File(ServletActionContext.getServletContext().getRealPath("/") + LOGOPHOTO);
Image logo = ImageIO.read(logoFile);
int lw = wideth/PHOTOPROPORTION;
int lh = lw*logo.getHeight(null)/logo.getWidth(null);
g.drawImage(logo, wideth - lw, height - lh, lw, lh, null);
g.dispose();
FileOutputStream out = new FileOutputStream(allpath + imageFileName); // ����ļ���
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // ��JPEG����
out.close();
if (wideth > height) {
height = 140 * height / wideth;
wideth = 140;
} else {
wideth = 140 * wideth / height;
height = 140;
}
tag = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(image, 0, 0, wideth, height, null); // ������С���ͼ
out = new FileOutputStream(allpath + breviaryPath); // ����ļ���
encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // ��JPEG����
out.close();
}
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
private static String getCaption(String fileName) {
if (fileName == null || fileName.lastIndexOf(".") == -1) {
return "";
}
int pos = fileName.lastIndexOf(".");
return fileName.substring(0, pos);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCitie() {
return citie;
}
public void setCitie(Long citie) {
this.citie = citie;
}
public String getRecordedTime() {
return recordedTime;
}
public void setRecordedTime(String recordedTime) {
this.recordedTime = recordedTime;
}
public String getMyFileFileName() {
return fileName;
}
public String getMyFileContentType() {
return contentType;
}
public void setMyFileContentType(String contentType) {
this.contentType = contentType;
}
public void setMyFileFileName(String fileName) {
this.fileName = fileName;
}
public String getImageFileName() {
return imageFileName;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getReturnValue() {
return returnValue;
}
public void setReturnValue(String returnValue) {
this.returnValue = returnValue;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
}
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import javax.imageio.ImageIO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* @author peng
*
*/
public class EditPictureAction extends ActionSupport {
private static final String[] PHOTOTYPE = {"bmp", "jpg", "jpeg", "gif","png", "ico", "jpe", "jfif" };
private static final String DEFAULTALBUM = "upfile/"; //存放图片的文件夹
private static final String LOGOPHOTO = "images/jxbq/1.gif"; //水印图片
private static final long serialVersionUID = 1L;
//照片与水印比例
private static final Integer PHOTOPROPORTION = 6;
private static final Log log = LogFactory.getLog(EditPictureAction.class);
private File myFile;
private String name;
private Long citie;
private Long categoryId;
private String returnValue;
private String recordedTime;
private String fileName;
private String contentType;
private String imageFileName;
/**
* 上传照片
*/
@Override
public String execute() {
try{
boolean isSuffix = true;
String suffix = getExtention(fileName).toLowerCase();
for (String string : PHOTOTYPE) {
if (("." + string).equals(suffix)) {
isSuffix = false;
}
}
if (isSuffix) {
returnValue = "UP_FILE_NO";
return SUCCESS;
}
String prefix = String.valueOf(new Date().getTime());
imageFileName = prefix + suffix;
String breviaryPath = prefix + "_s" + suffix;
String allpath = ServletActionContext.getServletContext().getRealPath("/") + DEFAULTALBUM;
createNewImage(myFile, allpath, imageFileName, breviaryPath);
String photoname = getCaption(fileName);
if(photoname.length() > 30) photoname = photoname.substring(0,30);
System.out.println("**********照片信息start***********");
System.out.println("photoname:" + photoname);
System.out.println("albumId:" + categoryId);
System.out.println("photodate:" + recordedTime);
System.out.println("cityId:" + citie);
System.out.println("photoBigPath:" + imageFileName);
System.out.println("photoSmallPath:" + breviaryPath);
System.out.println("**********照片信息end***********");
returnValue = "UP_FILE_OK";
return SUCCESS;
} catch (IOException e) {
log.error(e);
returnValue = "UP_FILE_NO";
return SUCCESS;
} catch (Exception e) {
log.error(e);
return ERROR;
}
}
/**
* 制作缩略图与水印图
* @param file
* @param allpath
* @param imageFileName
* @param breviaryPath
* @throws IOException
*/
public static void createNewImage(File file, String allpath,
String imageFileName, String breviaryPath) throws IOException {
Image image;
image = javax.imageio.ImageIO.read(file);
int wideth = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage tag = new BufferedImage(wideth, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.createGraphics();
g.drawImage(image, 0, 0, wideth, height, null); // ����ˮӡͼ
File logoFile = new File(ServletActionContext.getServletContext().getRealPath("/") + LOGOPHOTO);
Image logo = ImageIO.read(logoFile);
int lw = wideth/PHOTOPROPORTION;
int lh = lw*logo.getHeight(null)/logo.getWidth(null);
g.drawImage(logo, wideth - lw, height - lh, lw, lh, null);
g.dispose();
FileOutputStream out = new FileOutputStream(allpath + imageFileName); // ����ļ���
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // ��JPEG����
out.close();
if (wideth > height) {
height = 140 * height / wideth;
wideth = 140;
} else {
wideth = 140 * wideth / height;
height = 140;
}
tag = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(image, 0, 0, wideth, height, null); // ������С���ͼ
out = new FileOutputStream(allpath + breviaryPath); // ����ļ���
encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // ��JPEG����
out.close();
}
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
private static String getCaption(String fileName) {
if (fileName == null || fileName.lastIndexOf(".") == -1) {
return "";
}
int pos = fileName.lastIndexOf(".");
return fileName.substring(0, pos);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCitie() {
return citie;
}
public void setCitie(Long citie) {
this.citie = citie;
}
public String getRecordedTime() {
return recordedTime;
}
public void setRecordedTime(String recordedTime) {
this.recordedTime = recordedTime;
}
public String getMyFileFileName() {
return fileName;
}
public String getMyFileContentType() {
return contentType;
}
public void setMyFileContentType(String contentType) {
this.contentType = contentType;
}
public void setMyFileFileName(String fileName) {
this.fileName = fileName;
}
public String getImageFileName() {
return imageFileName;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getReturnValue() {
return returnValue;
}
public void setReturnValue(String returnValue) {
this.returnValue = returnValue;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
}
第二个文件 struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="demo" namespace="/" extends="struts-default">
<action name="EditPicture"
class="com.struts.EditPictureAction">
<interceptor-ref name="fileUploadStack" >
</interceptor-ref>
<result>
testupok.jsp
</result>
</action>
</package>
</struts>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="demo" namespace="/" extends="struts-default">
<action name="EditPicture"
class="com.struts.EditPictureAction">
<interceptor-ref name="fileUploadStack" >
</interceptor-ref>
<result>
testupok.jsp
</result>
</action>
</package>
</struts>
第三个文件 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>ajaxDWR</display-name>
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>ajaxDWR</display-name>
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
第四个文件 loadphoto.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!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" xml:lang="zh">
<head>
<link href="css/uploadfile.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="<%=request.getContextPath()%>/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="js/uploadfile.js"></script>
<title>照片</title>
</head>
<body>
<div id="context">
<div id="all"></div>
<div id="pro">
选择城市:<select id="c" style="width:120px; border:1px #BBBBBB solid;">
<option value="1">北京</option>
<option value="2">上海</option>
<option value="3">深圳</option>
<option value="4">南京</option>
<option value="5" selected="selected">武汉</option>
<option value="6">广州</option>
</select>
选择相册:<select id="getCategoryId" style="width:120px; border:1px #BBBBBB solid;">
<option value="1">相册一</option>
<option value="2">相册二</option>
<option value="3">相册三</option>
<option value="4">相册四</option>
<option value="5" selected="selected">相册五</option>
<option value="6">相册六</option>
</select>
选择时间<input id="getRecordedTime" name="getRecordedTime" class="Wdate" style="cursor:pointer;" type="text" onfocus="new WdatePicker(this,'%Y-%M-%D %h:%m:%s',true)" value="2008-03-03 19:28:17" />
</div>
<div id="buttons"></div>
<script type="text/javascript">
var list = new Array();
list.push({key:"c",value:"citie"});
list.push({key:"getCategoryId",value:"categoryId"});
list.push({key:"getRecordedTime",value:"recordedTime"});
var cr = new CreateLoad('all','buttons',5,'EditPicture.action',list);
cr.init();
</script>
</div>
</body>
</html>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!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" xml:lang="zh">
<head>
<link href="css/uploadfile.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="<%=request.getContextPath()%>/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="js/uploadfile.js"></script>
<title>照片</title>
</head>
<body>
<div id="context">
<div id="all"></div>
<div id="pro">
选择城市:<select id="c" style="width:120px; border:1px #BBBBBB solid;">
<option value="1">北京</option>
<option value="2">上海</option>
<option value="3">深圳</option>
<option value="4">南京</option>
<option value="5" selected="selected">武汉</option>
<option value="6">广州</option>
</select>
选择相册:<select id="getCategoryId" style="width:120px; border:1px #BBBBBB solid;">
<option value="1">相册一</option>
<option value="2">相册二</option>
<option value="3">相册三</option>
<option value="4">相册四</option>
<option value="5" selected="selected">相册五</option>
<option value="6">相册六</option>
</select>
选择时间<input id="getRecordedTime" name="getRecordedTime" class="Wdate" style="cursor:pointer;" type="text" onfocus="new WdatePicker(this,'%Y-%M-%D %h:%m:%s',true)" value="2008-03-03 19:28:17" />
</div>
<div id="buttons"></div>
<script type="text/javascript">
var list = new Array();
list.push({key:"c",value:"citie"});
list.push({key:"getCategoryId",value:"categoryId"});
list.push({key:"getRecordedTime",value:"recordedTime"});
var cr = new CreateLoad('all','buttons',5,'EditPicture.action',list);
cr.init();
</script>
</div>
</body>
</html>
第五个文件 uploadfile.js
var rowIndex = 0; //已经上传多少个文件
var File_cur = 1; //当前在上传哪个文件
var File_count = 10 ; //上传文件上限
var Return_str = "UP_FILE_OK"; //接收上传文件程序返回成功的字符串
var dell = true ; //当前状态,true表示未上传,false表示正在上传
var isIE=navigator.appName.indexOf("Microsoft")!=-1; //是否是IE浏览器
var valuelist = Object();
function addFile(x,y){
var File_listX = document.getElementById('File_list');
rowIndex = rowIndex + 1;
addRow(File_listX,-1,x,y);
document.getElementById('Utab_' + x).style.display="none";
try{
document.getElementById('Utab_' + (Number(x)+1)).style.display='block';
}catch(e){ }
}
function addRow(File_listX,n,x,y){
var Tr = File_listX.insertRow(n);
var Td = Tr.insertCell(n);
Td.innerHTML = y ;
Td.id = "textshow";
var Td1 = Tr.insertCell(n);
Td1.innerHTML = "<font color=808080 size=2>[已加入队列]";
Td1.id = "Ustatus_" + String(x) ;
Td1.name = "Ustatus_" + String(x) ;
var Td2 = Tr.insertCell(n);
Td2.innerHTML = "<a href=# onclick='deleteRow(this)'><img border=0 src='http://www.l99.com/skin1/images/sign_delete1.gif'></a> ";
}
function CreateLoad(divId,buttonsId,loadNUM,actionURI,list){
if(typeof loadNUM != "number"){
alert("loadNUM不是一个数字类型!");
return;
}
if(typeof list == "object" && list.constructor==Array){
valuelist = list;
}
File_count = loadNUM;
var arrayset;
var boxdiv = document.getElementById(divId);
var titles = document.createElement('table');
titles.id="File_list"
var row1 = titles.insertRow(0);
var cell1 = row1.insertCell(0);
cell1.id = "ONE";
var text1 = document.createTextNode('文件');
cell1.appendChild(text1);
var cell2 = row1.insertCell(1);
cell2.id = "TWO";
var text2 = document.createTextNode('状态');
cell2.appendChild(text2);
var cell3 = row1.insertCell(2);
cell3.id = "THREE";
var text3 = document.createTextNode('删除');
cell3.appendChild(text3);
boxdiv.appendChild(titles);
for(var i = 1;i <= File_count;i++){
arrayset = new Array();
var loadfile = document.createElement('div');
loadfile.id = "Utab_" + i;
loadfile.style.display = "none";
arrayset.push("<form enctype='multipart/form-data' method='post' target='uploadFrame' action='");
arrayset.push(actionURI);
arrayset.push("' name='form_");
arrayset.push(i);
arrayset.push("' id='form_");
arrayset.push(i);
arrayset.push("' ><table id='colltionbar'><tbody><tr><td style='text-align: left; padding-left: 10px;'>");
arrayset.push("第");
arrayset.push(i);
arrayset.push("个文件:选择文件");
if(valuelist.constructor==Array){
for(var number = 0 ; number < valuelist.length ; number = number+1){
arrayset.push("<input type='hidden' name='");
arrayset.push(valuelist[number].value);
arrayset.push("' id='");
arrayset.push(valuelist[number].value);
arrayset.push("_");
arrayset.push(i);
arrayset.push("' /></input>");
}
}
arrayset.push("<input type='file' name='myFile' id='R_file_");
arrayset.push(i);
arrayset.push("' size=30 onchange='addFile(");
arrayset.push(i);
arrayset.push(",this.value);' ></input></td></tr></tbody></table></form>");
loadfile.innerHTML = arrayset.join("");
arrayset = null;;
boxdiv.appendChild(loadfile);
}
var buttons = document.getElementById(buttonsId);
var button1 = document.createElement('input');
button1.type = "button";
button1.id = 'uploadBut';
button1.name="uploadBut";
button1.value="开始上传";
button1.onclick = function(){
InitUpload();
}
var button2 = document.createElement('input');
button2.type = "button";
button2.id = 'keepload';
button2.disabled=true;
button2.value="继续上传";
button2.onclick = function(){
window.location.reload();
}
buttons.appendChild(button1);
buttons.appendChild(button2);
var fileiframe = document.createElement('div');
fileiframe.innerHTML = "<iframe name='uploadFrame' height=30 width=300 id='uploadFrame' src='' style='display:none;'></iframe>";
buttons.appendChild(fileiframe);
}
CreateLoad.prototype = {
init : function()
{
document.getElementById('Utab_1').style.display = 'block';
}
}
//开始上传
function InitUpload() {
for(var i = 1;i <= rowIndex; i=i+1){
if(valuelist.constructor==Array){
for(var number = 0 ; number < valuelist.length ; number = number+1){
document.getElementById(valuelist[number].value + '_' + String(i)).value = document.getElementById(valuelist[number].key).value;
}
}
}
document.getElementById('uploadBut').disabled = true;
dell = false ;
hideAllform();
Uploads();
}
function hideAllform(){
for(var i=1;i<=File_count;i++){
try{
document.getElementById('Utab_' + String(i)).style.display="none";
}catch(e){ }
}
}
function Uploads() {
if (File_cur > File_count) {
alert("上传完毕");
document.getElementById('keepload').disabled = false;
return ;
}
window.frames['uploadFrame'].document.body.innerHTML = '';
var g_status = "" ;
var curTD = document.getElementById('Ustatus_'+String(File_cur)) ;
try{
g_status = document.getElementById('Ustatus_'+String(File_cur)).innerHTML ;
}catch(e){ }
if(g_status.length > 5 && g_status.indexOf("src") < 1 ){
curTD.innerHTML = "<img src='http://www.l99.com/skin1/images/loader.gif'><font color=blue size=2>上传中......";
document.getElementById('form_'+String(File_cur)).submit();
getUpLoadr();
}else{
File_cur++;
Uploads();
}
}
function getUpLoadr() {
var gstr = window.frames['uploadFrame'].document.body.innerHTML;
window.frames['uploadFrame'].document.body.innerHTML = '';
if (gstr.length < 1) {
//如果没有返回值则继续等待.
setTimeout("getUpLoadr()", 1000);
}else {
//有返回值则判断是否包含OK
if (gstr.indexOf(Return_str) != -1) {
document.getElementById('Ustatus_'+String(File_cur)).innerHTML = "<img src='http://www.l99.com/skin1/images/ok.gif' alt='done' title='上传成功' />";
}else {
document.getElementById('Ustatus_'+String(File_cur)).innerHTML = "<img src='http://www.l99.com/skin1/images/error.gif' alt='fail' title='上传失败,请查看错误信息' />上传失败";
}
File_cur++;
Uploads();
}
}
function deleteRow(obj){
if(dell){
try{
// IE 可以直接
var tr = obj.parentNode.parentNode;
tr.removeNode(true);
}catch(e){
// firefox 下必须这样。
var parent = tr.parentNode;
parent.removeChild(tr);
}
}else{
alert('正在上传中,请勿删除!');
}
}
var File_cur = 1; //当前在上传哪个文件
var File_count = 10 ; //上传文件上限
var Return_str = "UP_FILE_OK"; //接收上传文件程序返回成功的字符串
var dell = true ; //当前状态,true表示未上传,false表示正在上传
var isIE=navigator.appName.indexOf("Microsoft")!=-1; //是否是IE浏览器
var valuelist = Object();
function addFile(x,y){
var File_listX = document.getElementById('File_list');
rowIndex = rowIndex + 1;
addRow(File_listX,-1,x,y);
document.getElementById('Utab_' + x).style.display="none";
try{
document.getElementById('Utab_' + (Number(x)+1)).style.display='block';
}catch(e){ }
}
function addRow(File_listX,n,x,y){
var Tr = File_listX.insertRow(n);
var Td = Tr.insertCell(n);
Td.innerHTML = y ;
Td.id = "textshow";
var Td1 = Tr.insertCell(n);
Td1.innerHTML = "<font color=808080 size=2>[已加入队列]";
Td1.id = "Ustatus_" + String(x) ;
Td1.name = "Ustatus_" + String(x) ;
var Td2 = Tr.insertCell(n);
Td2.innerHTML = "<a href=# onclick='deleteRow(this)'><img border=0 src='http://www.l99.com/skin1/images/sign_delete1.gif'></a> ";
}
function CreateLoad(divId,buttonsId,loadNUM,actionURI,list){
if(typeof loadNUM != "number"){
alert("loadNUM不是一个数字类型!");
return;
}
if(typeof list == "object" && list.constructor==Array){
valuelist = list;
}
File_count = loadNUM;
var arrayset;
var boxdiv = document.getElementById(divId);
var titles = document.createElement('table');
titles.id="File_list"
var row1 = titles.insertRow(0);
var cell1 = row1.insertCell(0);
cell1.id = "ONE";
var text1 = document.createTextNode('文件');
cell1.appendChild(text1);
var cell2 = row1.insertCell(1);
cell2.id = "TWO";
var text2 = document.createTextNode('状态');
cell2.appendChild(text2);
var cell3 = row1.insertCell(2);
cell3.id = "THREE";
var text3 = document.createTextNode('删除');
cell3.appendChild(text3);
boxdiv.appendChild(titles);
for(var i = 1;i <= File_count;i++){
arrayset = new Array();
var loadfile = document.createElement('div');
loadfile.id = "Utab_" + i;
loadfile.style.display = "none";
arrayset.push("<form enctype='multipart/form-data' method='post' target='uploadFrame' action='");
arrayset.push(actionURI);
arrayset.push("' name='form_");
arrayset.push(i);
arrayset.push("' id='form_");
arrayset.push(i);
arrayset.push("' ><table id='colltionbar'><tbody><tr><td style='text-align: left; padding-left: 10px;'>");
arrayset.push("第");
arrayset.push(i);
arrayset.push("个文件:选择文件");
if(valuelist.constructor==Array){
for(var number = 0 ; number < valuelist.length ; number = number+1){
arrayset.push("<input type='hidden' name='");
arrayset.push(valuelist[number].value);
arrayset.push("' id='");
arrayset.push(valuelist[number].value);
arrayset.push("_");
arrayset.push(i);
arrayset.push("' /></input>");
}
}
arrayset.push("<input type='file' name='myFile' id='R_file_");
arrayset.push(i);
arrayset.push("' size=30 onchange='addFile(");
arrayset.push(i);
arrayset.push(",this.value);' ></input></td></tr></tbody></table></form>");
loadfile.innerHTML = arrayset.join("");
arrayset = null;;
boxdiv.appendChild(loadfile);
}
var buttons = document.getElementById(buttonsId);
var button1 = document.createElement('input');
button1.type = "button";
button1.id = 'uploadBut';
button1.name="uploadBut";
button1.value="开始上传";
button1.onclick = function(){
InitUpload();
}
var button2 = document.createElement('input');
button2.type = "button";
button2.id = 'keepload';
button2.disabled=true;
button2.value="继续上传";
button2.onclick = function(){
window.location.reload();
}
buttons.appendChild(button1);
buttons.appendChild(button2);
var fileiframe = document.createElement('div');
fileiframe.innerHTML = "<iframe name='uploadFrame' height=30 width=300 id='uploadFrame' src='' style='display:none;'></iframe>";
buttons.appendChild(fileiframe);
}
CreateLoad.prototype = {
init : function()
{
document.getElementById('Utab_1').style.display = 'block';
}
}
//开始上传
function InitUpload() {
for(var i = 1;i <= rowIndex; i=i+1){
if(valuelist.constructor==Array){
for(var number = 0 ; number < valuelist.length ; number = number+1){
document.getElementById(valuelist[number].value + '_' + String(i)).value = document.getElementById(valuelist[number].key).value;
}
}
}
document.getElementById('uploadBut').disabled = true;
dell = false ;
hideAllform();
Uploads();
}
function hideAllform(){
for(var i=1;i<=File_count;i++){
try{
document.getElementById('Utab_' + String(i)).style.display="none";
}catch(e){ }
}
}
function Uploads() {
if (File_cur > File_count) {
alert("上传完毕");
document.getElementById('keepload').disabled = false;
return ;
}
window.frames['uploadFrame'].document.body.innerHTML = '';
var g_status = "" ;
var curTD = document.getElementById('Ustatus_'+String(File_cur)) ;
try{
g_status = document.getElementById('Ustatus_'+String(File_cur)).innerHTML ;
}catch(e){ }
if(g_status.length > 5 && g_status.indexOf("src") < 1 ){
curTD.innerHTML = "<img src='http://www.l99.com/skin1/images/loader.gif'><font color=blue size=2>上传中......";
document.getElementById('form_'+String(File_cur)).submit();
getUpLoadr();
}else{
File_cur++;
Uploads();
}
}
function getUpLoadr() {
var gstr = window.frames['uploadFrame'].document.body.innerHTML;
window.frames['uploadFrame'].document.body.innerHTML = '';
if (gstr.length < 1) {
//如果没有返回值则继续等待.
setTimeout("getUpLoadr()", 1000);
}else {
//有返回值则判断是否包含OK
if (gstr.indexOf(Return_str) != -1) {
document.getElementById('Ustatus_'+String(File_cur)).innerHTML = "<img src='http://www.l99.com/skin1/images/ok.gif' alt='done' title='上传成功' />";
}else {
document.getElementById('Ustatus_'+String(File_cur)).innerHTML = "<img src='http://www.l99.com/skin1/images/error.gif' alt='fail' title='上传失败,请查看错误信息' />上传失败";
}
File_cur++;
Uploads();
}
}
function deleteRow(obj){
if(dell){
try{
// IE 可以直接
var tr = obj.parentNode.parentNode;
tr.removeNode(true);
}catch(e){
// firefox 下必须这样。
var parent = tr.parentNode;
parent.removeChild(tr);
}
}else{
alert('正在上传中,请勿删除!');
}
}
第六个文件 uploadfile.css
@CHARSET "UTF-8";
body { overflow-x:hidden; background:#FFFFFF; font-size:13px; color:#333333;}
#context { width:620px; margin:50px auto; padding:10px; border: 1px #CCCCCC solid;}
#File_list { width: 600px; border: 1px #C8C8C8 solid;}
#File_list #ONE {width: 400px;}
#File_list #TWO {width: 150px;}
#File_list #THREE { width: 45px;}
#colltionbar { width: 595px; border: 1px #C8C8C8 solid; background-color:#EAEAEA;}
#centerbar { height:40px;border:1px;width:595px;}
.photocontext { width:600px; font-size:13px; color:#333333; clear:both; overflow-x:hidden; text-align:left; border: 1px solid #C8C8C8;}
#buttons { margin:auto; text-align:center;}
#buttons input { background-color:#B5B5B5; cursor:pointer; height:22px; line-height:20px;margin: 20px;}
.photocontext .citySelect { width:120px;}
.thisButton a {color:#FC5A0A; text-decoration:none;}
.thisButton a:hover {text-decoration:underline;}
#pro {margin: auto;}
body { overflow-x:hidden; background:#FFFFFF; font-size:13px; color:#333333;}
#context { width:620px; margin:50px auto; padding:10px; border: 1px #CCCCCC solid;}
#File_list { width: 600px; border: 1px #C8C8C8 solid;}
#File_list #ONE {width: 400px;}
#File_list #TWO {width: 150px;}
#File_list #THREE { width: 45px;}
#colltionbar { width: 595px; border: 1px #C8C8C8 solid; background-color:#EAEAEA;}
#centerbar { height:40px;border:1px;width:595px;}
.photocontext { width:600px; font-size:13px; color:#333333; clear:both; overflow-x:hidden; text-align:left; border: 1px solid #C8C8C8;}
#buttons { margin:auto; text-align:center;}
#buttons input { background-color:#B5B5B5; cursor:pointer; height:22px; line-height:20px;margin: 20px;}
.photocontext .citySelect { width:120px;}
.thisButton a {color:#FC5A0A; text-decoration:none;}
.thisButton a:hover {text-decoration:underline;}
#pro {margin: auto;}
第七个文件 testupok.jsp
<%=request.getAttribute("returnValue")%>
效果
一共7个文件
在IE与firefox下测试通过
var cr = new CreateLoad('all','buttons',5,'EditPicture.action',list); 需要5个参数
第一个是 显示文件信息的div的id
第二个是显示按钮的div的id
第三个是一次做多上传多少个文件
第四个是文件上传的action
第五个是和文件一起需要传递的附加值 以数组的方式传递
var list = new Array();list.push({key:"c",value:"citie"});
key是前台赋值组件的id ,value是后台接收的name
诚求js达人帮我优化uploadfile.js,
声明 :大家互相学习 :) 转载请注明出处
- 用iframe做不刷新批量上传
- 用iframe实现不刷新整个页面上传图片
- 【WebGUI】——iframe+lua页面不刷新上传文件
- Iframe和jquery结合实现不刷新上传
- 用iframe实现提交表单不刷新
- Iframe实现不刷新
- iframe无刷新上传文件
- Iframe 无刷新上传文件
- struts2+iframe无刷新上传
- PHP用iframe实现文件异步上传(无刷新)
- 利用隐藏iframe处理文件上传,本页不刷新,仿ajax
- iframe提交,做页面无刷新 cao
- ajax iframe jsp 无刷新上传文件
- php使用Iframe无刷新上传
- 利用iframe实现无刷新图片上传
- iframe实现无刷新上传文件
- 利用iframe实现表单无刷新上传
- 无刷新多文件上传(iframe)
- Bochs虚拟机的使用及Linux的初步接触
- JasperReport+iReport高级报表设计实战
- One-Jar之旅
- 动态装载问题的研究
- Java实现的插入法建立B+树
- 用iframe做不刷新批量上传
- SUN GlassFish拥抱Spring
- Delphi使用VB控件全攻略
- 为什么开源产业不同于沃尔玛
- Oracle开放Oracle App Server与Spring Framework的集成代码
- Spring框架:项目名称起源
- Rod在Oracle World大会后的感想(二)
- VB控件在C#中的使用
- Rod在Oracle World大会后的感想(一)