第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 id="progress_bar"

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

<div id="progress"

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 id="msg"></div>

</form>

   

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

</body>

</html>

   

   

   

   

   

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);

}

   

}

   

posted on 2016-03-01 09:33  胖先生  阅读(392)  评论(0编辑  收藏  举报