第02篇上传文件进度条示例

中午,本该午睡的时间,但是总是感觉有事情没有完成,一直想自己做一个关于进度条上传的示例,所以兴趣所致,简单做了一个版本,这个版本中还算是有点意思,至少可以用到了所谓的监听器,呵呵! 我就直接上代码

第02篇上传文件进度条示例

   

   

   

   

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%

//项目的发布路径,例如: /rabc

String path = request.getContextPath();

/*

全路径,形式如下: http://127.0.0.1:8001/rbac/

request.getScheme() ——> http 获取协议

request.getServerName() --> 127.0.0.1 获取服务名

request.getServerPort() --> 8001 获取端口号

path --> /rbac 获取访问的路径 路

*/

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML>

<html>

<head>

<%--

参考文章:http://www.cnblogs.com/muqianying/archive/2012/03/16/2400280.html

--%>

<base href="<%=basePath%>">

<meta charset="UTF-8">

<title>胖先生:83604162</title>

<script type="text/javascript" src="resource/jquery.js"></script>

<script>

var timer = null;

function beginUpload() {

$("#progress_bar").show();

jQuery("#progress").css("width","0px");

timer = setInterval("getUploadMeter()", 500);

}

function getUploadMeter() {

$.post("get_percent.shxt", function(data) {

var json = eval("(" + data + ")");

jQuery("#progress").css("width", json.percentage / 100 * 400 + "px");

jQuery("#msg").css("padding", "1px").css("width", "400px").css("height", "20px").html("Finishing: " + json.percentage + "%");

if(json.percentage=="100.0"){

window.clearInterval(timer);

   

}

});

}

</script>

</head>

<body>

<h2>Upload File with Progress Bar</h2>

<form action="upload.shxt" method="post" enctype="multipart/form-data" onsubmit="beginUpload()" target="upload">

<input type="file" name="formFile" style="width:300px; height:30px; font-size: 14px">

<br />

<br />

进度条显示...

<br />

 

<div

style="width: 400px; height: 20px; display: none; border: 1px solid black;">

<div

style="background-color: red; height: 20px; width: 0px;"></div>

</div>

   

<br />

<input type="submit" value="Upload" style="width:100px; height:30px; font-size: 20px">

<div ></div>

</form>

   

<iframe name="upload" frameBorder="0" noResize scrolling="no" width="0" height="0"></iframe>

</body>

</html>

   

   

   

   

第02篇上传文件进度条示例

   

package com.hanpang.servlet;

   

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.text.DecimalFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Random;

   

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

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.ProgressListener;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.commons.fileupload.util.Streams;

import org.apache.commons.io.FilenameUtils;

   

/**

* Servlet implementation class UploadServlet

*/

@WebServlet("/upload.shxt")

public class UploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

   

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

* response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

   

Map<String, Object> map = new HashMap<String,Object>();

   

// 判断是否为上传请求

if (ServletFileUpload.isMultipartContent(request)) {

try {

// 1.获取绝对路径

String path = request.getServletContext().getRealPath("/upload");

   

File folder = new File(path);

if (!folder.isDirectory()) {

folder.mkdirs();

}

   

// Create a factory for disk-based file items

DiskFileItemFactory factory = new DiskFileItemFactory();

   

// Set factory constraints

factory.setSizeThreshold(3000 * 1024 * 1024);

String tempPath = request.getServletContext().getRealPath("/tmp");

File temp = new File(tempPath);

if (!temp.isDirectory()) {

temp.mkdirs();

}

factory.setRepository(temp);

   

/// Create a new file upload handler

ServletFileUpload upload = new ServletFileUpload(factory);

   

// Add listener, implement the update method --关键步骤

upload.setProgressListener(new UploadProgressListener(request));

   

// Set overall request size constraint

upload.setSizeMax(3000 * 1024 * 1024);

// Parse the request

   

List<FileItem> items = upload.parseRequest(request);

   

// Process the uploaded items

Iterator<FileItem> iterator = items.iterator();

//迭代

while(iterator.hasNext()){

FileItem fileItem = iterator.next();

//获取表单name中对应的名词

String fieldName = fileItem.getFieldName();

   

InputStream is = fileItem.getInputStream();

   

//判断是不是普通控件--重要

if(fileItem.isFormField()){

map.put(fieldName, Streams.asString(is, "UTF-8"));

//如果获取普通控件的值value

//System.out.println("是普通控件"+Streams.asString(is, "UTF-8"));

}else{

//获取文件的名词

String fileName = fileItem.getName();

//判断上传文件名称是否存在

if(fileName.trim().length()>0){

//获取后缀名

String ext = FilenameUtils.getExtension(fileName);

//方式二

String newFileName = (new Date()).getTime()+"_"+(new Random().nextInt(1000))+"."+ext;

File out_file = new File(path+"/"+newFileName);//绝对路径拼接

OutputStream os = new FileOutputStream(out_file);

   

byte[] bytes = new byte[1024];

int length = -1;

while((length=is.read(bytes))!=-1){

os.write(bytes, 0, length);

}

   

map.put(fieldName, newFileName);

map.put("REAL_NAME", fileName);

   

   

   

is.close();

os.flush();

os.close();

}

   

}

}

   

} catch (Exception e) {

e.printStackTrace();

}

}

}

   

/**

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// TODO Auto-generated method stub

doGet(request, response);

}

   

class UploadProgressListener implements ProgressListener {

private HttpServletRequest request;

private long megaBytes = -1;

private DecimalFormat df = new DecimalFormat("#00.0");

   

UploadProgressListener(HttpServletRequest request) {

this.request = request;

}

   

public void update(long bytesRead, long bytesTotal, int items) {

// if no process, then return

long mBytes = bytesRead / 1024;

if (megaBytes == mBytes) {

return;

}

megaBytes = mBytes;

   

double percent = (double) bytesRead * 100 / (double) bytesTotal;

// also can use log to show the progress.

System.out.println(df.format(percent));

request.getSession().setAttribute("UPLOAD_PERCENTAGE", df.format(percent));

}

};

   

}

   

package com.hanpang.servlet;

   

import java.io.IOException;

import java.io.PrintWriter;

   

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

   

/**

* Servlet implementation class GetUploadPercentServlet

*/

@WebServlet("/get_percent.shxt")

public class GetUploadPercentServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

   

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

HttpSession session = request.getSession();

Object is_begin = session.getAttribute("UPLOAD_PERCENTAGE");

if (is_begin == null)

return;

if ("0".equals(is_begin.toString()))

return;

   

PrintWriter out = response.getWriter();

Object upload_percentage = session.getAttribute("UPLOAD_PERCENTAGE");

out.write("{percentage:'" + upload_percentage.toString() + "'}");//JSON数据

out.flush();

}

   

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

doGet(request, response);

}

   

}

   

第02篇上传文件进度条示例

更多相关文章
  • node实现http上传文件进度条-我们到底能走多远系列37
    我们到底能走多远系列(37) 扯淡: 又到了一年一度的跳槽季,相信你一定准备好了,每每跳槽,总有好多的路让你选,我们的未来也正是这一个个选择机会组合起来的结果,所以尽可能的找出自己想要的是什么再做决定.共勉! 主题: 实现上传文件时,在页面中展现进度条的基本原理如图: 1,客户端先发起上传文件请求, ...
  • 找到一个好东西.可以在struts2上显示进度条.  [url]http://www.davidjc.com/ajaxfileupload/demo!input.action[/url]      
  • jquery文件上传插件进度条
    jquery文件上传插件|进度条一.Uploadify官网:http://www.uploadify.com/下载地址:http://down.51cto.com/data/577863详细参数配置示例: http://xuqin.blog.51cto.com/5183168/1047084二.
  • 前端代码: <form id= "uploadForm"> <p >指定文件名: <input type="text" name="filename" value= ""/></ ...
  • jQuery.uploadify-----文件上传带进度条,支持多文件上传的插件
    借鉴别人总结的uploadify:基于jquery的文件上传插件,支持ajax无刷新上传,多个文件同时上传,上传进行进度显示,控制文件上传大小,删除已上传文件. uploadify有两个版本,一个用flash,一个是html5.html5的需要付费~所以这里只说flash版本的用法. uploadi ...
  • Web上传文件的三种解决方案 这里我要使用的是form法.通过为表单元素设置enctype=”multipart/form-data”属性,让表单提交的数据以二进制编码的方式提交,在接收此请求的Servlet中用二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传. 表单元素的encty ...
  • PHP使用APC获取上传文件进度
    今天发现使用PHP的APC也能获取上传文件的进度.这篇文章就说下如何做. 安装APC 首先安装APC的方法和其他PHP模块的方法没什么两样,网上能找出好多 phpinfo可以看到APC的默认配置有: apc.rfc1867 看apc.rfc1867这个配置项: http://cn2.php.net/ ...
  • 页面技术:HTML5 + AJAX ( jQuery) 后台技术:Servlet 3.0 服务器:Tomcat 7.0 jQuery版本:1.9.1 ;*loaded/tot); //已经上传的百分比 $("#son").html( per +"%" ); $ ...
一周排行
  • 以下内容摘自笔者2008年的新作--<网管员面试宝典>一书.  测试一下你对IP地址的理解能力,大家先不看题后的解答,看自己能做出多少题. 面试题1:以下说法正确的是().A. C类地址就是局域网用的IP ...
  • 如果开发项目需要解析音频文件流,可以使用 iOS 的 Audio File Stream Services. Audio File Stream Services 支持的音频数据格式:AIFFAIFCWAVECAFN ...
  • index.html内容:<iframe  name="mpage" onload="AdaptorHeight()" style="border-style: ...
  • 说明 在windows中经常用到将程序添加到桌面或者是开始菜单,乘着休息时间就做了这么一个快捷的工具. 程序展示: 用法 1. 命令行(CMD命令窗口) 命令: C:\Users\Administrator>[ ...
  • LinuxLB集群知识、如何用LVS方式实现LB集群
    LB负载均衡的目的是为了提高访问的并发性和服务器的性能.实现 LB 的方式主要有软件方式和 ...
  • samba服务器,我相信大家都不陌生,主要用来实现windows和linux之间的资源共享,网上比较多的是采用rpm安装包的方式安装,我个人也觉得rpm方式安装比较方便容易,如果没什么特别需求,还是用这种吧!我这里介 ...
  • chkconfigchkconfig 命令用来设定和查询不同运行级上的系统服务  注:谨记chkconfig不是立即自动禁止或激活一个服务,它只是简单的改变了符号连接.语法解释 :chkconfig       -- ...
  • 由于开发要求开发环境需要在每天晚上自动部署,因此花了一天时间写了个基于jboss的自动部署脚本#!/bin/bash #deploy jboos script # Usage() { echo "Usage ...
  • PHP 脚本在服务器上执行,然后向浏览器发送回纯 HTML 结果. 基础 PHP 语法 PHP 脚本可放置于文档中的任何位置. PHP 脚本以 <?php 开头,以 ?> 结尾: <?php // ...
  • [原创]批处理性能测试