Solved

file upload

Posted on 2012-04-03
26
482 Views
Last Modified: 2012-08-13
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...
0
Comment
Question by:shragi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 16
  • 10
26 Comments
 
LVL 27

Expert Comment

by:rrz
ID: 37802182
0
 

Author Comment

by:shragi
ID: 37802197
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
 
LVL 27

Expert Comment

by:rrz
ID: 37802230
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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
LVL 27

Expert Comment

by:rrz
ID: 37802241
0
 

Author Comment

by:shragi
ID: 37802279
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
 
LVL 27

Expert Comment

by:rrz
ID: 37802394
I couldn't find the War either.
0
 

Author Comment

by:shragi
ID: 37803094
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
 
LVL 27

Expert Comment

by:rrz
ID: 37803148
>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
 

Author Comment

by:shragi
ID: 37803168
ok can you help me with packaging up all the pieces of code
0
 
LVL 27

Expert Comment

by:rrz
ID: 37803190
Ok, I will work on it later today when I have time.
0
 
LVL 27

Expert Comment

by:rrz
ID: 37803222
Are you using Tomcat ? What version ?
0
 

Author Comment

by:shragi
ID: 37803326
currently I am using Jboss 5.0,
but i also have tomcat 6.0.35 installed...
0
 
LVL 27

Expert Comment

by:rrz
ID: 37803389
Ok, good.
0
 

Author Comment

by:shragi
ID: 37803487
I am trying to package the code pieces, but was stuck at a point.
where should i place the Ajax implementation ?
0
 
LVL 27

Expert Comment

by:rrz
ID: 37803594
I am working on same thing. They really didn't give all the pieces. Working...
0
 

Author Comment

by:shragi
ID: 37803844
let me know once you are done... thank you
0
 
LVL 27

Expert Comment

by:rrz
ID: 37803902
At the moment,I am trying to get a bare bones demo going.
0
 
LVL 27

Expert Comment

by:rrz
ID: 37804096
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
 

Author Comment

by:shragi
ID: 37806553
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
 
LVL 27

Expert Comment

by:rrz
ID: 37806590
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
 

Author Comment

by:shragi
ID: 37806649
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
 
LVL 27

Expert Comment

by:rrz
ID: 37808716
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
 
LVL 27

Expert Comment

by:rrz
ID: 37818105
I did some testing on the internet. It didn't perform  very well. More work needs to done.
0
 
LVL 27

Expert Comment

by:rrz
ID: 37818123
Which browsers are your targets ?
0
 

Author Comment

by:shragi
ID: 37830028
I am targeting IE browsers - but it would be great if it works for all browsers...
0
 
LVL 27

Accepted Solution

by:
rrz earned 500 total points
ID: 37830377
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

Featured Post

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question