I am trying to write an api to monitor the upload percent of a file. I am trying to use `apache fileUpload` for this. When I try to parse the request it return `null`
Here is my api for upload
def uploadFile(){
// create file upload factory and upload servlet
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// set file upload progress listener
Upload listener = new Upload();
HttpSession session = request.getSession();
session.setAttribute("LISTENER", listener);
// upload servlet allows to set upload listener
upload.setProgressListener(listener);
List uploadedItems = null;
FileItem fileItem = null;
String filePath = "/projects/test";
try
{
// iterate over all uploaded files
uploadedItems = upload.parseRequest(request);
Iterator i = uploadedItems.iterator();
while (i.hasNext())
{
fileItem = (FileItem) i.next();
if (fileItem.isFormField() == false)
{
if (fileItem.getSize() > 0)
{
File uploadedFile = null;
String myFullFileName = fileItem.getName(),
myFileName = "",
slashType = (myFullFileName.lastIndexOf("\\")
> 0) ? "\\" : "/"; // Windows or UNIX
int startIndex = myFullFileName.lastIndexOf(slashType);
// Ignore the path and get the filename
myFileName = myFullFileName.substring(startIndex + 1, myFullFileName.length());
// Create new File object
uploadedFile = new File(filePath, myFileName);
// Write the uploaded file to the system
fileItem.write(uploadedFile);
}
}
}
}
catch (FileUploadException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
`status api`
def getStatus(){
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
Upload listener = null;
StringBuffer buffy = 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 = (Upload)session.getAttribute("LISTENER");
if (listener == null)
{
return;
}
else
{
// Get the meta information
bytesRead = listener.getBytesRead();
contentLength = listener.getContentLength();
}
}
System.out.println("Bytes Read : " + bytesRead + " total : " + contentLength)
}
`ProgressListener`
public class Upload implements ProgressListener {
private volatile long
bytesRead = 0L,
contentLength = 0L,
item = 0L;
public Upload()
{
super();
}
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;
}
}
Any other solution is welcome.