iframe+struts2文件上传实时进度条

前台jsp内容:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
	<script type="text/javascript" src="bootstrap/js/jquery-1.11.1.js"></script>
	<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
	<script type="text/javascript">
		//这个方法用于提交表单
		function submitFile() {
			$("#fileForm").attr("action","myFileUpload");
			$("#fileForm").submit();
		}
		//接收后台返回的数据并进行处理
		function upload(msg) {
			if(msg == "服务器异常") {
				$("#msgSpan").html("服务器异常");
			}else {//获取到文件上传的进度,设置进度条的宽度
				var progressPercent = parseFloat(msg);
				var progressWidth = $("#progressParentDiv").width()*progressPercent;
				$("#progressId").width(progressWidth);
			}
		}
	</script>
  </head>
  
  <body>
    <form id="fileForm" action="myFileUpload" method="post" enctype="multipart/form-data" target="fileIframe">
    	<input type="file" name="file"/>
    	<input id="submitButton" type="button" value="上传" οnclick="submitFile();">
    </form>
    <div id="progressParentDiv" class="progress" style="margin-left:5px;margin-right:5px;">
		<div id="progressId" class="progress-bar" role="progressbar" aria-valuenow="60" 
				aria-valuemin="0" aria-valuemax="100" style="width: 0;">
		</div>
	</div>
	<span id="msgSpan"></span>
    <iframe id="fileIframe" name="fileIframe"></iframe>
  </body>
</html>

 后台controller:

package cn.bdx.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class TestFileUpload extends ActionSupport {

	private File file;
	private String fileFileName;
	private String fileContentType;

	/**
	 * 接收前台发送的参数
	 */
	public void testFileUpload() {
		HttpServletResponse resp = ServletActionContext.getResponse();
		HttpServletRequest req = ServletActionContext.getRequest();
		resp.setContentType("text/html;charset=utf-8");// 设置返回消息的字符集
		resp.setHeader("pragma", "no-cache");
		resp.setHeader("cache-control", "no-cache");
		resp.setHeader("expires", "0");
		// 获取文件上传到服务器的文件路径(我这里是上传到项目的upload文件夹中)
		String root = ServletActionContext.getServletContext().getRealPath("/upload");
		try {
			InputStream is = new FileInputStream(file);
			OutputStream os = new FileOutputStream(new File(root,fileFileName));

			byte[] buffer = new byte[1024];
			long length = 0;
			double progressLength = 0;
			double totalLength = file.length();// 文件总长度
			double progressPercent = 0;// 文件上传进度
			while ((length = is.read(buffer, 0, buffer.length)) != -1) {
				os.write(buffer);
				progressLength += length;
				progressPercent = progressLength / totalLength;
				this.sendMsg(resp, "parent.upload("+progressPercent+")");
			}
			os.close();
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
			this.sendMsg(resp, "parent.upload('服务器异常')");
		}
	}

	/**
	 * 向客户端发送消息
	 * 
	 * @param resp
	 * @param msg
	 * @throws IOException
	 */
	private void sendMsg(HttpServletResponse resp, String msg) {
		PrintWriter out = null;
		try {
			out = resp.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
			out.println("<script type='text/javascript'>parent.upload('服务器异常')</script>");
		}
		out.println("<script type='text/javascript'>" + msg + "</script>");
		out.println("----------------------------------------");
		out.println("----------------------------------------");
		out.println("----------------------------------------");
		out.println("----------------------------------------");
		out.println("----------------------------------------");
		out.flush();
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

}

 struts.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	<constant name="struts.devMode" value="true" />
	<constant name="struts.multipart.maxSize" value="550000000"/>
	<package name="default" namespace="/" extends="struts-default">
		<action name="myFileUpload" class="cn.bdx.controller.TestFileUpload" method="testFileUpload"></action>
	</package>
</struts>

 web.xml文件,这个只是struts2的配置需要,也贴在这里,

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" 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>Struts Blank</display-name>

	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
</web-app>

 再导入struts2需要的jar包就可以运行了。

注:这里使用单个iframe在上传2M以上的文件时总是感觉非常的慢,暂时不知道什么原因造成的,希望了解的能够指点一下,非常感谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值