package com.server.action.back;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpSession;
import com.server.data.State;
import com.opensymphony.xwork2.ActionSupport;
// aAction
public class FileProgressAction extends ActionSupport{
private State state;
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public String execute() throws Exception {
HttpSession session=ServletActionContext.getRequest().getSession();
this.state=(State)session.getAttribute("state");
if(state==null){
//System.out.println("action is null");
state=new State();
state.setCurrentItem(0);
}else{
Double a=Double.parseDouble(state.getReadedBytes()+"");
Double b=Double.parseDouble(state.getTotalBytes()+"");
double result=a/b*100;
state.setRate((int)result);
//System.out.println("action:"+state.getRate());
}
return "success";
}
}
// 注册Actionpackage com.server.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
import com.nibiru.server.data.State;
public class FileUploadListener implements ProgressListener{
private HttpSession session;
public FileUploadListener(HttpServletRequest request) {
session = request.getSession();
State state = new State();
session.setAttribute("state", state);
}
public void update(long readedBytes, long totalBytes, int currentItem) {
//System.out.println("update:"+readedBytes+";"+totalBytes+";"+currentItem);
State state = (State) session.getAttribute("state");
state.setReadedBytes(readedBytes);
state.setTotalBytes(totalBytes);
state.setCurrentItem(currentItem);
}
}
package com.server.data;
public class State {
private long readedBytes = 0L;
private long totalBytes = 0L;
private int currentItem = 0;
private int rate=0;
public long getReadedBytes() {
return readedBytes;
}
public void setReadedBytes(long readedBytes) {
this.readedBytes = readedBytes;
}
public long getTotalBytes() {
return totalBytes;
}
public void setTotalBytes(long totalBytes) {
this.totalBytes = totalBytes;
}
public int getCurrentItem() {
return currentItem;
}
public void setCurrentItem(int currentItem) {
this.currentItem = currentItem;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
}
package com.server.util;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.StrutsConstants;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.dispatcher.multipart.MultiPartRequest;
public class MyMultiPartRequest implements MultiPartRequest{
static final Logger LOG = LoggerFactory.getLogger(MultiPartRequest.class);
// maps parameter name -> List of FileItem objects
protected Map> files = new HashMap>();
// maps parameter name -> List of param values
protected Map> params = new HashMap>();
// any errors while processing this request
protected List errors = new ArrayList();
protected long maxSize;
@Inject(StrutsConstants.STRUTS_MULTIPART_MAXSIZE)
public void setMaxSize(String maxSize) {
this.maxSize = Long.parseLong(maxSize);
}
/**
* Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
* multipart classes (see class description).
*
* @param saveDir the directory to save off the file
* @param request the request containing the multipart
* @throws java.io.IOException is thrown if encoding fails.
*/
public void parse(HttpServletRequest request, String saveDir) throws IOException {
try {
processUpload(request, saveDir);
} catch (FileUploadException e) {
LOG.warn("Unable to parse request", e);
errors.add(e.getMessage());
}
}
private void processUpload(HttpServletRequest request, String saveDir) throws FileUploadException, UnsupportedEncodingException {
for (FileItem item : parseRequest(request, saveDir)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Found item " + item.getFieldName());
}
if (item.isFormField()) {
processNormalFormField(item, request.getCharacterEncoding());
} else {
processFileField(item);
}
}
}
private void processFileField(FileItem item) {
LOG.debug("Item is a file upload");
// Skip file uploads that don't have a file name - meaning that no file was selected.
if (item.getName() == null || item.getName().trim().length() < 1) {
LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
return;
}
List values;
if (files.get(item.getFieldName()) != null) {
values = files.get(item.getFieldName());
} else {
values = new ArrayList();
}
values.add(item);
files.put(item.getFieldName(), values);
}
private void processNormalFormField(FileItem item, String charset) throws UnsupportedEncodingException {
LOG.debug("Item is a normal form field");
List values;
if (params.get(item.getFieldName()) != null) {
values = params.get(item.getFieldName());
} else {
values = new ArrayList();
}
// note: see http://jira.opensymphony.com/browse/WW-633
// basically, in some cases the charset may be null, so
// we're just going to try to "other" method (no idea if this
// will work)
if (charset != null) {
values.add(item.getString(charset));
} else {
values.add(item.getString());
}
params.put(item.getFieldName(), values);
}
private List parseRequest(HttpServletRequest servletRequest, String saveDir) throws FileUploadException {
DiskFileItemFactory fac = createDiskFileItemFactory(saveDir);
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setSizeMax(maxSize);
/*�Լ��½�������*/
FileUploadListener progressListener = new FileUploadListener(servletRequest);
upload.setProgressListener(progressListener);//����Լ��ļ�����
return upload.parseRequest(createRequestContext(servletRequest));
}
private DiskFileItemFactory createDiskFileItemFactory(String saveDir) {
DiskFileItemFactory fac = new DiskFileItemFactory();
// Make sure that the data is written to file
fac.setSizeThreshold(0);
if (saveDir != null) {
fac.setRepository(new File(saveDir));
}
return fac;
}
/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFileParameterNames()
*/
public Enumeration getFileParameterNames() {
return Collections.enumeration(files.keySet());
}
/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getContentType(java.lang.String)
*/
public String[] getContentType(String fieldName) {
List items = files.get(fieldName);
if (items == null) {
return null;
}
List contentTypes = new ArrayList(items.size());
for (FileItem fileItem : items) {
contentTypes.add(fileItem.getContentType());
}
return contentTypes.toArray(new String[contentTypes.size()]);
}
/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFile(java.lang.String)
*/
public File[] getFile(String fieldName) {
List items = files.get(fieldName);
if (items == null) {
return null;
}
List fileList = new ArrayList(items.size());
for (FileItem fileItem : items) {
File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
if(fileItem.isInMemory() && storeLocation!=null && !storeLocation.exists()) {
try {
storeLocation.createNewFile();
} catch (IOException e) {
if(LOG.isErrorEnabled()){
LOG.error("Cannot write uploaded empty file to disk: " + storeLocation.getAbsolutePath(),e);
}
}
}
fileList.add(storeLocation);
}
return fileList.toArray(new File[fileList.size()]);
}
/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFileNames(java.lang.String)
*/
public String[] getFileNames(String fieldName) {
List items = files.get(fieldName);
if (items == null) {
return null;
}
List fileNames = new ArrayList(items.size());
for (FileItem fileItem : items) {
fileNames.add(getCanonicalName(fileItem.getName()));
}
return fileNames.toArray(new String[fileNames.size()]);
}
/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFilesystemName(java.lang.String)
*/
public String[] getFilesystemName(String fieldName) {
List items = files.get(fieldName);
if (items == null) {
return null;
}
List fileNames = new ArrayList(items.size());
for (FileItem fileItem : items) {
fileNames.add(((DiskFileItem) fileItem).getStoreLocation().getName());
}
return fileNames.toArray(new String[fileNames.size()]);
}
/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getParameter(java.lang.String)
*/
public String getParameter(String name) {
List v = params.get(name);
if (v != null && v.size() > 0) {
return v.get(0);
}
return null;
}
/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getParameterNames()
*/
public Enumeration getParameterNames() {
return Collections.enumeration(params.keySet());
}
/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getParameterValues(java.lang.String)
*/
public String[] getParameterValues(String name) {
List v = params.get(name);
if (v != null && v.size() > 0) {
return v.toArray(new String[v.size()]);
}
return null;
}
/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getErrors()
*/
public List getErrors() {
return errors;
}
/**
* Returns the canonical name of the given file.
*
* @param filename the given file
* @return the canonical name of the given file
*/
private String getCanonicalName(String filename) {
int forwardSlash = filename.lastIndexOf("/");
int backwardSlash = filename.lastIndexOf("\\");
if (forwardSlash != -1 && forwardSlash > backwardSlash) {
filename = filename.substring(forwardSlash + 1, filename.length());
} else if (backwardSlash != -1 && backwardSlash >= forwardSlash) {
filename = filename.substring(backwardSlash + 1, filename.length());
}
return filename;
}
/**
* Creates a RequestContext needed by Jakarta Commons Upload.
*
* @param req the request.
* @return a new request context.
*/
private RequestContext createRequestContext(final HttpServletRequest req) {
return new RequestContext() {
public String getCharacterEncoding() {
return req.getCharacterEncoding();
}
public String getContentType() {
return req.getContentType();
}
public int getContentLength() {
return req.getContentLength();
}
public InputStream getInputStream() throws IOException {
InputStream in = req.getInputStream();
if (in == null) {
throw new IOException("Missing content in the request");
}
return req.getInputStream();
}
};
}
@Override
public void cleanUp() {
// TODO Auto-generated method stub
}
}
var id=0;
function addressAction(){
$.post(
'UploadProgress',
function(data){
var readedMB = (data.state.readedBytes/1024/1024).toString();
var totalMB = (data.state.totalBytes/1024/1024).toString();
readedMB = readedMB.substring(0,readedMB.lastIndexOf(".") + 3);
totalMB = totalMB.substring(0,totalMB.lastIndexOf(".") + 3);
if(data.currentItem===0){
$("#m").text('0%');
}else if(data.state.rate!=100){
$("#r").text(data.state.rate+'%');
$("#m").text(readedMB+'MB'+'/'+totalMB+'MB');
}else{
$("#r").text(data.state.rate+'%');
$("#m").text(readedMB+'MB'+'/'+totalMB+'MB');
window.clearInterval(id);
}
$("#img").html("");
var num=parseInt(data.state.rate/5);
for(var i=1;i<=num;i++){
$("#img").append("
");
}
for(var j=1;j<=20-num;j++){
$("#img").append("
");
}
},
'json'
);
}
id=window.setInterval(addressAction,1000);
var width=window.screen.availWidth;
var height=window.screen.availHeight;
var left=window.innerWidth;
var top=window.innerHeight;
var scrollTop=document.body.scrollTop;
$("body").append("");
$("#zzc").css("position","fixed").css("left","0px").css("top","0px").css("z-index","100").css("opacity","0.5");
$("#zzc").width(width);
$("#zzc").height(height);
$("body").append("");
$("#asd").css("position","fixed").css("left","0px").css("top","0px").css("z-index","500");
$("#asd").width(width);
$("#asd").height(height);
$("#asd").append("上传进度 ")
$("#img").html("");
$("#m").html("");
$("#progress").show().css({"position":"absolute","z-index":500}); #progress{
left:800px;
top:350px;
padding: 10px 0;
background-color:#4ba3fc;
position:absolute;
width:400px;
height:150px;
border:0px solid #fff;
border-radius: 5px;
display: none;
}
#progressBar
{
border:0px solid black;
width:300px;
height:20px;
margin-left:50px;
margin-top:20px;
padding: 2px 0;
}
#title{
height:20px;
background-color:#4ba3fc;
pading:-10px;
text-align:center;
margin-top:10px;
font-family: Microsoft Yahei;
font-size:17px;
}
#info{
font-family: Microsoft Yahei;
font-size:17px;
text-align:center;
margin-top:10px;
}
#rate{
font-family: Microsoft Yahei;
font-size:17px;
text-align:center;
margin-top:10px;
}
SSH实现上传进度条
最新推荐文章于 2024-02-02 11:22:36 发布