Tuesday, 9 December 2014

Progress bar don't work correctly:percents of upload not see



UploadFileServlet.java:



package servlets;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

/**
*
* @author Serg Bash
*/
public class UploadFileServlet extends HttpServlet {

private static final long serialVersionUID = 2740693677625051632L;

public UploadFileServlet()
{
super();
}


private boolean isMultipart;
private String filePath;
//Maximum file size, 100mb
private final int maxFileSize = 1024 * 1024 * 100;
//Maximum memory size, 1gb
private final int maxMemSize = 1024 * 1024 * 1000000;
private File file;
HttpServletRequest httpServlReq;

@Override
public void init() {
// Get the file location where it would be stored. "D:\\temp" or "C:\\Program Files\temp"
filePath = this.getServletContext().getRealPath("\\");
}

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);

PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
FileUploadListener listener = null;
StringBuffer buffer = new StringBuffer();
long bytesRead = 0, contentLength = 0;
// Make sure the session has started
if (session == null)
{
return;
}
else if (session != null)
{
// Check to see if we've created the listener object yet
listener = (FileUploadListener)session.getAttribute("LISTENER");

if (listener == null)
{
return;
}
else
{
// Get the meta information
bytesRead = listener.getBytesRead();
contentLength = listener.getContentLength();
}
}

/*
* XML Response Code
*/
response.setContentType("text/xml");

buffer.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
buffer.append("<response>\n");
buffer.append("\t<bytes_read>" + bytesRead + "</bytes_read>\n");
buffer.append("\t<content_length>" + contentLength + "</content_length>\n");

// Check to see if we're done
if (bytesRead == contentLength)
{
buffer.append("\t<finished />\n");
// No reason to keep listener in session since we're done
session.setAttribute("LISTENER", null);
}
else
{
// Calculate the percent complete
long percentComplete = ((100 * bytesRead) / contentLength);
buffer.append("\t<percent_complete>" + percentComplete + "</percent_complete>\n");
}
buffer.append("</response>\n");
out.println(buffer.toString());
out.flush();
out.close();
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
httpServlReq=request;
// String title = request.getParameter("title");
// String description = request.getParameter("description");
// String keywords = request.getParameter("keywords");
response.setContentType("text/html;charset=UTF-8");
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (!isMultipart) {
out.println("<h1>No file uploaded</h1>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("D:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);

try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath
+ fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(filePath
+ fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
}
}
} catch (Exception ex) {
out.println(ex.getMessage());
}
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet UploadFile</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Image upload!</h1>");
out.println("</body>");
out.println("</html>");

File f = new File(file.getAbsoluteFile().toString());
uploadFile("http://ift.tt/1wJxFk9", f, "title", "description", "keywords");
file.delete();
}

public void uploadFile(String url, File sendFile, String title, String description, String keywords) throws UnsupportedEncodingException, IOException {
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(url);
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
FileUploadListener listener = new FileUploadListener();
HttpSession session = httpServlReq.getSession();
session.setAttribute("LISTENER", listener);
upload.setProgressListener(listener);
MultipartEntity reqEntity = new MultipartEntity(){


public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new UploadStream(outstream, listener));
}
};
FileInputStream is = null;
// Add authentication variables.
reqEntity.addPart("key", new StringBody("******"));
reqEntity.addPart("secret", new StringBody("********"));
reqEntity.addPart("sig", new StringBody(md5("********" + "upload")));
//Add title, description, etc.
reqEntity.addPart("title", new StringBody(title));
reqEntity.addPart("description", new StringBody(description));
reqEntity.addPart("keywords", new StringBody(keywords));
// Add the media file:
reqEntity.addPart("media", new InputStreamBody(is = new FileInputStream(sendFile), sendFile.toString()));
// Execute POST request.
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
if (response != null) {
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
}
}

public static final String md5(final String input) {

try {

// Create MD5 Hash
MessageDigest messageDigest = java.security.MessageDigest.getInstance("MD5");
messageDigest.update(input.getBytes());
byte messageDigestBytes[] = messageDigest.digest();

// Create Hex String
StringBuffer md5String = new StringBuffer();

for (int i = 0; i < messageDigestBytes.length; i++) {

// Convert to Hex
String h = Integer.toHexString(0xFF & messageDigestBytes[i]);

// Make sure we have leading zeros.
while (h.length() < 2) {
h = "0" + h;
}

// Append to our final String
md5String.append(h);

}

// Return our MD5 Hash
return md5String.toString();

} catch (NoSuchAlgorithmException e) {

// In case the device does not support MD5.
e.printStackTrace();

}

return "";
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

}


FileUploadListener.java



package servlets;
import org.apache.commons.fileupload.ProgressListener;

public class FileUploadListener implements ProgressListener
{
private volatile long
bytesRead = 0L,
contentLength = 0L,
item = 0L;

public FileUploadListener()
{
super();
}

@Override
public void update(long aBytesRead, long aContentLength, int anItem)
{
bytesRead = aBytesRead;
contentLength = aContentLength;
item = anItem;
}

public long getBytesRead()
{
return bytesRead;
}

public long getContentLength()
{
return contentLength;
}

public long getItem()
{
return item;
}
}


uploadFile.html



<html>
<head>
<title>Ajax File Upload</title>
<script language="javascript">
var req;

function ajaxFunction()
{
var url = "UploadFileServlet";

if (window.XMLHttpRequest) // Non-IE browsers
{
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;

try
{
req.open("GET", url, true);
}
catch (e)
{
alert(e);
}
req.send(null);
}
else if (window.ActiveXObject) // IE Browsers
{
req = new ActiveXObject("Microsoft.XMLHTTP");

if (req)
{
req.onreadystatechange = processStateChange;
req.open("GET", url, true);
req.send();
}
}
}

function processStateChange()
{
/**
* State Description
* 0 The request is not initialized
* 1 The request has been set up
* 2 The request has been sent
* 3 The request is in process
* 4 The request is complete
*/
if (req.readyState == 4)
{
if (req.status == 200) // OK response
{
var xml = req.responseXML;

// No need to iterate since there will only be one set of lines
var isNotFinished = xml.getElementsByTagName("finished")[0];
var myBytesRead = xml.getElementsByTagName("bytes_read")[0];
var myContentLength = xml.getElementsByTagName("content_length")[0];
var myPercent = xml.getElementsByTagName("percent_complete")[0];

// Check to see if it's even started yet
if ((isNotFinished == null) && (myPercent == null))
{
document.getElementById("initializing").style.visibility = "visible";

// Sleep then call the function again
window.setTimeout("ajaxFunction();", 100);
}
else
{
document.getElementById("initializing").style.visibility = "hidden";
document.getElementById("progressBarTable").style.visibility = "visible";
document.getElementById("percentCompleteTable").style.visibility = "visible";
document.getElementById("bytesRead").style.visibility = "visible";

myBytesRead = myBytesRead.firstChild.data;
myContentLength = myContentLength.firstChild.data;

if (myPercent != null) // It's started, get the status of the upload
{
myPercent = myPercent.firstChild.data;

document.getElementById("progressBar").style.width = myPercent + "%";
document.getElementById("bytesRead").innerHTML = myBytesRead + " of " +
myContentLength + " bytes read";
document.getElementById("percentComplete").innerHTML = myPercent + "%";

// Sleep then call the function again
window.setTimeout("ajaxFunction();", 100);
}
else
{
document.getElementById("bytesRead").style.visibility = "hidden";
document.getElementById("progressBar").style.width = "100%";
document.getElementById("percentComplete").innerHTML = "Done!";
}
}
}
else
{
alert(req.statusText);
}
}
}
</script>
</head>
<body>
<iframe id="uploadFrameID" name="uploadFrame" height="0" width="0" frameborder="0" scrolling="yes"></iframe>
<form id="myForm" enctype="multipart/form-data" method="post" target="uploadFrame"
action="UploadFileServlet" onsubmit="ajaxFunction()">
Title:<input type="text" name="title" id="title" /><br />
Description:<input type="text" name="description" id="description" /><br />
Keywords:<input type="text" name="keywords" id="keywords" /><br />
<input type="file" name="txtFile" id="txtFile" /><br />
<input type="submit" id="submitID" name="submit" value="Upload" /></br>
</form>

<!-- Add hidden DIVs for updating and the progress bar (just a table) below the form -->
<div id="initializing" style="visibility: hidden; position: absolute; top: 100px;">
<table width="100%" style="border: 1px; background-color: black;">
<tr>
<td>
<table width="100%" style="border: 1px; background-color: black; color: white;">
<tr>
<td align="center">
<b>Initializing Upload...</b>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>

<div id="progressBarTable" style="visibility: hidden; position: absolute; top: 100px;">
<table width="100px" style="border: 1px; background-color: black; color: white;">
<tr>
<td>
<table id="progressBar" width="0px"
style="border: 1px; width: 0px; background-color: blue;">
<tr>
<td>&nbsp;</td>
</tr>
</table>
</td>
</tr>
</table>
<table width="100%" style="background-color: white; color: black;">
<tr>
<td align="center" nowrap="nowrap">
<span id="bytesRead" style="font-weight: bold;">&nbsp;</span>
</td>
</tr>
</table>
</div>

<div id="percentCompleteTable" align="center"
style="visibility: hidden; position: absolute; top: 100px;">
<table width="100%" style="border: 1px;">
<tr>
<td>
<table width="100%" style="border: 1px;">
<tr>
<td align="center" nowrap="nowrap">
<span id="percentComplete" style="color: white; font-weight: bold;">&nbsp;</span>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>


I write app, which upload files with HttpPost class.All application work fine, but don't work correctly progress-bar: its only show: "Done", when file uploaded to server and don't show percents of uploaded file in bites (in FileUploadListener). In application without HttpPost progress-bar work fine. I don't understand, what's a problem? Any ideas for help me?


No comments:

Post a Comment