file upload

I am looking for a tool or code which i can embed in my project for uploading a file.
currently i am doing a simple file upload, but I want to modify it - i mean i want to provide multiple file upload feature and also show the file upload progress...

I found plupload (http://www.plupload.com/index.php) for this purpose,
but I am not able to use that one.. because of my limitation in php.

so I was wondering is there any other code or something else...
which allows me to add file upload feature  to my java project
so that I can see the progress of file upload and also upload multiple files at a time...
shragiAsked:
Who is Participating?
 
rrzConnect With a Mentor Commented:
I did some more work(see below). You will have do testing yourself.  It works on my desktop for IE8 and  Firefox11. In Chrome18 the ajax doesn't work unless the form has a target attribute to send the response to a iframe or another window.
package rrz;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.util.*;
public class UploadServlet3 extends HttpServlet {
    @Override
    public void init(){
              System.out.println("init of UploadServlet3");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
       PrintWriter out = response.getWriter();
       response.setContentType("text/html");
       out.write("<html><body>");
       out.print("Request content length is " + request.getContentLength() + "<br/>"); 
       boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       if(isMultipart){
                  FileUploadListener listener = new FileUploadListener();
                  HttpSession session = request.getSession(false);
                  if(session == null){
                           out.write("Cookies must be enabled to maintain session.");
                           return;
                  }		       		
                  session.setAttribute("listener", listener);
                  ServletFileUpload upload = new ServletFileUpload();
                  upload.setProgressListener(listener);
           try{
                  FileItemIterator iter = upload.getItemIterator(request);
                  FileItemStream item = null;
                  String name = "";
                  InputStream stream = null;
                  while (iter.hasNext()){
                                         item = iter.next();
                                         name = item.getFieldName();
                                         stream = item.openStream();
                    if(item.isFormField()){
                       out.write("Form field " + name + ": " + Streams.asString(stream) + "<br/>");
                    }else {
                          name = item.getName();
                          if(name != null && !"".equals(name)){
                             String fileName = new File(item.getName()).getName();
                             out.write("Client file: " + item.getName() + " <br/>with file name "
                                                        + fileName + " was uploaded.<br/>");
                             File file = new File(getServletContext().getRealPath("/uploads/" + fileName));
                             FileOutputStream fos = new FileOutputStream(file);
                             long fileSize = Streams.copy(stream, fos, true);
                             out.write("Size was " + fileSize + " bytes <br/>");
                             out.write("File Path is " + file.getPath() + "<br/>");
                             //System.out.println("bytesRead = " + listener.getTheBytesRead() + " bytes");
                             try{
                                 Thread.sleep(500); // just to slow things down on my desktop
                                 //System.out.println("sleeping in doPost of UploadServlet3");
                                }catch(InterruptedException ie){}
                          }
                       }
                  }
              } catch(FileUploadException fue) {out.write("fue!!!!!!!!!");}
       } else out.print("wrong type of request");
       out.write("</body></html>");
  }
  @Override
  protected void doGet(HttpServletRequest request,HttpServletResponse response) 
    throws ServletException, IOException {
      //System.out.println("doGet received in UploadServlet3");
      PrintWriter out = response.getWriter();
      response.setContentType("text/html");
      HttpSession session = request.getSession(false);
      FileUploadListener listener = null; 
      if(session == null){
           //System.out.println("session null in doget");
           out.write("session null in doget");
      } else{
             //System.out.println("session not null in doget");
             listener = (FileUploadListener)session.getAttribute("listener");
             if(listener == null){
                  System.out.print(" 0");
                  out.write("0");
             } else{
                    System.out.print(" " + listener.getPercentDone());
                    out.write("" + listener.getPercentDone());
                 }
         }
         
  }
} 

Open in new window

<%
  session.removeAttribute("listener");
%>
<html>
<head>
<title>UploadFile.jsp</title>
<script language="javascript">
var req;
var percent = 0;
function upload(){
    document.uploadForm.submit();
    ajax();
}
function ajax(){
   var url = "upload3?nocache=" + new Date().getTime();
   if(window.XMLHttpRequest) req = new XMLHttpRequest(); 
   else req = new ActiveXObject("Microsoft.XMLHTTP");
   req.onreadystatechange = processStateChange;
     try{ 
         req.open("get", url, true);
     } catch(e){ alert(e);}
   req.send();
}
function processStateChange(){
   if(req.readyState == 4){
       percent = req.responseText;
       document.getElementById("progress").innerHTML = percent;
       if(percent != 100){ 
             window.setTimeout("ajax();", 75); // test to determine proper delay
       }
   }
}
</script>
</head>
<body>
            <form enctype='multipart/form-data' action='<%=request.getContextPath()%>/upload3' 
                    name="uploadForm" method="post" >
                   <input type='file' name='file1'/>
                   <input type='file' name='file2'/>
                   <input type='file' name='file3'/>
                   <input type='file' name='file4'/>
                   <input type='file' name='file5'/>
                   <input type='file' name='file6'/>
                   <input type='file' name='file7'/>
                   <input type='file' name='file8'/>
                   type your message: <input type="text" name="message" />
                   <input type='button' value='Submit' onclick="upload();"/>  
            </form>
            Upload is <span id="progress" style="background-color: white; color: red;"> 0 </span> % complete.
</body></html> 

Open in new window

0
 
rrzCommented:
0
 
shragiAuthor Commented:
yup but that did not solve my complete purpose....
no file upload progress and no can't select multiple files at a time to upload.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
rrzCommented:
Did you see the third page of that article ?    
http://javaboutique.internet.com/tutorials/java-upload/index-3.html   
It uses  AJAX and a ProgressListener.
0
 
rrzCommented:
0
 
shragiAuthor Commented:
http://javaboutique.internet.com/tutorials/java-upload/index-3.html

looks like the above link is going to solve my problem...
it was written that we can download the code as war file.
but i cannot find that location.... it would be great if i can get that location....
0
 
rrzCommented:
I couldn't find the War either.
0
 
shragiAuthor Commented:
the two solutions has problems....

the first one doesn't have source code and the second one is not free...

so do you have any other solutions....
0
 
rrzCommented:
>the first one doesn't have source code  
You mean the one at
http://javaboutique.internet.com/tutorials/java-upload/index-3.html 
It does have code but it is in pieces. If you need help, then we could work on it together. I don't if it meets all your requirements. But we could give it a try.
0
 
shragiAuthor Commented:
ok can you help me with packaging up all the pieces of code
0
 
rrzCommented:
Ok, I will work on it later today when I have time.
0
 
rrzCommented:
Are you using Tomcat ? What version ?
0
 
shragiAuthor Commented:
currently I am using Jboss 5.0,
but i also have tomcat 6.0.35 installed...
0
 
rrzCommented:
Ok, good.
0
 
shragiAuthor Commented:
I am trying to package the code pieces, but was stuck at a point.
where should i place the Ajax implementation ?
0
 
rrzCommented:
I am working on same thing. They really didn't give all the pieces. Working...
0
 
shragiAuthor Commented:
let me know once you are done... thank you
0
 
rrzCommented:
At the moment,I am trying to get a bare bones demo going.
0
 
rrzCommented:
Sorry, I have been kind of busy here at work.
I couldn't get the ajax code in the article to work. So, I made some bare bones code just to demonstrate the upload and the listener. All it does now is print to the console. Maybe later(tonight or tomorrow) I can add the ajax part.  I found different code for the listener at
http://www.avajava.com/tutorials/lessons/how-do-i-monitor-the-progress-of-a-file-upload-to-a-servlet.html?page=2
package rrz;
import org.apache.commons.fileupload.ProgressListener;
public class FileUploadListener implements ProgressListener {
	private long num100Ks = 0;
	private long theBytesRead = 0;
	private long theContentLength = -1;
	private int whichItem = 0;
	private int percentDone = 0;
	private boolean contentLengthKnown = false;
	public void update(long bytesRead, long contentLength, int items) {
		if (contentLength > -1) {
			contentLengthKnown = true;
		}
		theBytesRead = bytesRead;
		theContentLength = contentLength;
		whichItem = items;

		long nowNum100Ks = bytesRead / 100000;
		// Only run this code once every 100K
		if (nowNum100Ks > num100Ks) {
			num100Ks = nowNum100Ks;
			if (contentLengthKnown) {
				percentDone = (int) Math.round(100.00 * bytesRead / contentLength);
			}
			System.out.println(getMessage());
		}
	}
	public String getMessage() {
		if (theContentLength == -1) {
			return "" + theBytesRead + " of Unknown-Total bytes have been read.";
		} else {
			return "" + theBytesRead + " of " + theContentLength + " bytes have been read (" + percentDone + "% done).";
		}
	}
	public long getNum100Ks() {
		return num100Ks;
	}
	public void setNum100Ks(long num100Ks) {
		this.num100Ks = num100Ks;
	}
	public long getTheBytesRead() {
		return theBytesRead;
	}
	public void setTheBytesRead(long theBytesRead) {
		this.theBytesRead = theBytesRead;
	}
	public long getTheContentLength() {
		return theContentLength;
	}
	public void setTheContentLength(long theContentLength) {
		this.theContentLength = theContentLength;
	}
	public int getWhichItem() {
		return whichItem;
	}
	public void setWhichItem(int whichItem) {
		this.whichItem = whichItem;
	}
	public int getPercentDone() {
		return percentDone;
	}
	public void setPercentDone(int percentDone) {
		this.percentDone = percentDone;
	}
	public boolean isContentLengthKnown() {
		return contentLengthKnown;
	}
	public void setContentLengthKnown(boolean contentLengthKnown) {
		this.contentLengthKnown = contentLengthKnown;
	}
}

Open in new window

 Here's the present state of my Servlet. I mapped it to /upload3  and used that as the action in the JSP's form below here.
package rrz;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.util.*;
public class UploadServlet3 extends HttpServlet {
    @Override
    public void init(){
              System.out.println("init of UploadServlet3");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
       PrintWriter out = response.getWriter();
       out.print("Request content length is " + request.getContentLength() + "<br/>"); 
       out.print("Request content type is " + request.getHeader("Content-Type") + "<br/>");
       boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       if(isMultipart){
                  FileUploadListener listener = new FileUploadListener();
                  HttpSession session = request.getSession();		       
                  session.removeAttribute("LISTENER");		
                  session.setAttribute("LISTENER", listener);
                  ServletFileUpload upload = new ServletFileUpload();
                  upload.setProgressListener(listener);
           try{
                  FileItemIterator iter = upload.getItemIterator(request);
                  FileItemStream item = null;
                  String name = "";
                  InputStream stream = null;
                  while (iter.hasNext()){
                                         item = iter.next();
                                         name = item.getFieldName();
                                         stream = item.openStream();
                    if(item.isFormField()){out.write("Form field " + name + ": " 
                                               + Streams.asString(stream) + "<br/>");}
                    else {
                          name = item.getName();
                          if(name != null && !"".equals(name)){
                             String fileName = new File(item.getName()).getName();
                             out.write("Client file: " + item.getName() + " <br/>with file name "
                                                        + fileName + " was uploaded.<br/>");
                             File file = new File(getServletContext().getRealPath("/uploads/" + fileName));
                             FileOutputStream fos = new FileOutputStream(file);
                             long fileSize = Streams.copy(stream, fos, true);
                             out.write("Size was " + fileSize + " bytes <br/>");
                             out.write("File Path is " + file.getPath() + "<br/>");
                             System.out.println("bytesRead in UploadServlet3 = " + listener.getTheBytesRead() + " bytes");
                             try{
                                 Thread.sleep(2000); // just to slow things down on my desktop
                                 System.out.println("sleeping in doPost of UploadServlet3");
                                }catch(InterruptedException ie){}
                          }
                       }
                  }
              } catch(FileUploadException fue) {out.write("fue!!!!!!!!!");}
       }
  }

} 

Open in new window

Here is my JSP.
<html>
<head>
<title>UploadFile.jsp</title>
</head>
<body>
            <form enctype='multipart/form-data' action='<%=request.getContextPath()%>/upload3' method="post">
                   <input type='file' name='file1'/>
                   <input type='file' name='file2'/>
                   <input type='file' name='file3'/>
                   typemessage: <input type="text" name="message" />
                   <input Type='submit' value='Submit'/>  
            </form>

</body></html>

Open in new window

 Did you download the fileupload jar so that you can run this? I was testing with 1mb files. I added some sleep code just to slow it down on my desktop.
0
 
shragiAuthor Commented:
when you say fileupload jar file i assume you are talking about commons-fileupload.jar
I downloaded them and tried to execute the program.
i got java.io.FileNotFoundException

and i event tried the other solution looks like it is not complete...

http://www.avajava.com/tutorials/lessons/how-do-i-monitor-the-progress-of-a-file-upload-to-a-servlet.html?page=2


I appreciate your help and let me know if you had any update on this....
0
 
rrzCommented:
I found some more code.  
http://www.roseindia.net/ajax/File-Upload.shtml 
I couldn't get that to though.  I am still working on this  at the moment. But I have business to attend to soon.
0
 
shragiAuthor Commented:
ok and one more thing... I am able to execute your code and as you said I am can see the progress on the console...
0
 
rrzCommented:
I found some time to work on this. It still needs a lot of work to be really great.  You should test it by selecting 8 files into the form. That way you can actually see it working. Uploading happens too fast on the desktop. So, I added sleeping between files to enable testing. I commented out my debug lines but I left them in the code. I tested in IE8 browser. It doesn't seem to work in Google Chrome. I don't have time right now to figure out why.
package rrz;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.util.*;
public class UploadServlet3 extends HttpServlet {
    @Override
    public void init(){
              System.out.println("init of UploadServlet3");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
       PrintWriter out = response.getWriter();
       out.print("Request content length is " + request.getContentLength() + "<br/>"); 
       boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       if(isMultipart){
                  FileUploadListener listener = new FileUploadListener();
                  HttpSession session = request.getSession(false);		       		
                  session.setAttribute("listener", listener);
                  ServletFileUpload upload = new ServletFileUpload();
                  upload.setProgressListener(listener);
           try{
                  FileItemIterator iter = upload.getItemIterator(request);
                  FileItemStream item = null;
                  String name = "";
                  InputStream stream = null;
                  while (iter.hasNext()){
                                         item = iter.next();
                                         name = item.getFieldName();
                                         stream = item.openStream();
                    if(item.isFormField()){
                       out.write("Form field " + name + ": " + Streams.asString(stream) + "<br/>");
                    }else {
                          name = item.getName();
                          if(name != null && !"".equals(name)){
                             String fileName = new File(item.getName()).getName();
                             out.write("Client file: " + item.getName() + " <br/>with file name "
                                                        + fileName + " was uploaded.<br/>");
                             File file = new File(getServletContext().getRealPath("/uploads/" + fileName));
                             FileOutputStream fos = new FileOutputStream(file);
                             long fileSize = Streams.copy(stream, fos, true);
                             out.write("Size was " + fileSize + " bytes <br/>");
                             out.write("File Path is " + file.getPath() + "<br/>");
                             //System.out.println("bytesRead = " + listener.getTheBytesRead() + " bytes");
                             try{
                                 Thread.sleep(500); // just to slow things down on my desktop
                                 //System.out.println("sleeping in doPost of UploadServlet3");
                                }catch(InterruptedException ie){}
                          }
                       }
                  }
              } catch(FileUploadException fue) {out.write("fue!!!!!!!!!");}
       } else out.print("wrong type of request");
  }
  @Override
  protected void doGet(HttpServletRequest request,HttpServletResponse response) 
    throws ServletException, IOException {
      //System.out.println("doGet received in UploadServlet3");
      PrintWriter out = response.getWriter();
      HttpSession session = request.getSession(false);
      FileUploadListener listener = null; 
      if(session == null){
           //System.out.println("session null in doget");
           //out.write("session null in doget");
      } else{
             //System.out.println("session not null in doget");
             listener = (FileUploadListener)session.getAttribute("listener");
             if(listener == null){
                  //System.out.println("listener null in doget");
             } else {
                     //System.out.println("listener  not null in doget");
                     System.out.print(" " + listener.getPercentDone());
                     out.write("" + listener.getPercentDone());
                    }
           }
         
  }
} 

Open in new window

 
package rrz;
import org.apache.commons.fileupload.ProgressListener;
public class FileUploadListener implements ProgressListener {
	private long num100Ks = 0;
	private long theBytesRead = 0;
	private long theContentLength = -1;
	private int whichItem = 0;
	private int percentDone = 0;
	private boolean contentLengthKnown = false;
	public void update(long bytesRead, long contentLength, int items) {
		if (contentLength > -1) {
			contentLengthKnown = true;
		}
		theBytesRead = bytesRead;
		theContentLength = contentLength;
		whichItem = items;

		long nowNum100Ks = bytesRead / 10000;
		// Only run this code once every 10K
		if (nowNum100Ks > num100Ks) {
			num100Ks = nowNum100Ks;
			if (contentLengthKnown) {
				percentDone = (int) Math.round(100.00 * bytesRead / contentLength);
			}
			//System.out.println(getMessage());
		}
	}
	public String getMessage() {
		if (theContentLength == -1) {
			return "" + theBytesRead + " of Unknown-Total bytes have been read.";
		} else {
			return "" + theBytesRead + " of " + theContentLength + " bytes have been read (" + percentDone + "% done).";
		}
	}
	public long getNum100Ks() {
		return num100Ks;
	}
	public void setNum100Ks(long num100Ks) {
		this.num100Ks = num100Ks;
	}
	public long getTheBytesRead() {
		return theBytesRead;
	}
	public void setTheBytesRead(long theBytesRead) {
		this.theBytesRead = theBytesRead;
	}
	public long getTheContentLength() {
		return theContentLength;
	}
	public void setTheContentLength(long theContentLength) {
		this.theContentLength = theContentLength;
	}
	public int getWhichItem() {
		return whichItem;
	}
	public void setWhichItem(int whichItem) {
		this.whichItem = whichItem;
	}
	public int getPercentDone() {
		return percentDone;
	}
	public void setPercentDone(int percentDone) {
		this.percentDone = percentDone;
	}
	public boolean isContentLengthKnown() {
		return contentLengthKnown;
	}
	public void setContentLengthKnown(boolean contentLengthKnown) {
		this.contentLengthKnown = contentLengthKnown;
	}
}

Open in new window

 
<%
  session.removeAttribute("listener");
%>
<html>
<head>
<title>UploadFile.jsp</title>
<script language="javascript">
var req;
function upload(){
    document.uploadForm.submit();
    ajax();
}
function ajax(){
   var url = "<%=request.getContextPath()%>/upload3?nocache=" + new Date().getTime();
   if(window.XMLHttpRequest) req = new XMLHttpRequest(); 
   else req = new ActiveXObject("Microsoft.XMLHTTP");
   req.onreadystatechange = processStateChange;
     try{ 
         req.open("get", url, true);
     } catch(e){ alert(e);}
   req.send();
}
function processStateChange(){
   if (req.readyState==4 && req.status==200){
       var percent = req.responseText;
       document.getElementById("progress").innerHTML = percent;
       if(percent != 100){ 
             window.setTimeout("ajax();", 2);
       }
   }
}
</script>
</head>
<body>
            <form enctype='multipart/form-data' action='<%=request.getContextPath()%>/upload3' 
                    name="uploadForm" method="post">
                   <input type='file' name='file1'/>
                   <input type='file' name='file2'/>
                   <input type='file' name='file3'/>
                   <input type='file' name='file4'/>
                   <input type='file' name='file5'/>
                   <input type='file' name='file6'/>
                   <input type='file' name='file7'/>
                   <input type='file' name='file8'/>
                   type your message: <input type="text" name="message" />
                   <input type='button' value='Submit' onclick="upload();"/>  
            </form>
            Upload is <span id="progress" style="background-color: white; color: red;"> 0 </span> % complete.
</body></html> 

Open in new window

0
 
rrzCommented:
I did some testing on the internet. It didn't perform  very well. More work needs to done.
0
 
rrzCommented:
Which browsers are your targets ?
0
 
shragiAuthor Commented:
I am targeting IE browsers - but it would be great if it works for all browsers...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.