jGuru
Register Email     Password Forgot your
password?
HOME FAQS FORUMS DOWNLOADS ARTICLES PEERSCOPE LEARN

  Search   jGuru Search Help

Question How do I upload a file to my servlet or JSP?
Topics Java:API:JSP, Java:API:Servlets:Files:Uploading
Author Alex Chaffee PREMIUM
Created Sep 3, 1999 Modified Jan 11, 2003


Answer

On the client side, the client's browser must support form-based upload. Most modern browsers do, but there's no guarantee. For example,

<FORM ENCTYPE='multipart/form-data'
 method='POST' action='/myservlet'>
<INPUT TYPE='file' NAME='mptest'>
<INPUT TYPE='submit' VALUE='upload'>
</FORM>
The input type &amp;quot;file&amp;quot; brings up a button for a file select box on the browser together with a text field that takes the file name once selected. The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse.

When the user clicks the "Upload" button, the client browser locates the local file and sends it using HTTP POST, encoded using the MIME-type multipart/form-data. When it reaches your servlet, your servlet must process the POST data in order to extract the encoded file. You can learn all about this format in RFC 1867.

Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are a number of libraries available that do. Some of these assume that you will be writing the file to disk; others return the data as an InputStream.

Once you process the form-data stream into the uploaded file, you can then either write it to disk, write it to a database, or process it as an InputStream, depending on your needs. See How can I access or create a file or folder in the current directory from inside a servlet? and other questions in the Servlets:Files Topic for information on writing files from a Servlet.

Please note that you can't access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that.

[This FAQ based on earlier posts by Thomas Moore, Detlef Pleiss (dpleiss@os-net.de), and others.]



Is this item helpful?  yes  no     Previous votes   Yes: 25  No: 1



Comments and alternative answers

Comment on this FAQ entry

Jun Inamori has written a class called org.apache....
Alex Chaffee PREMIUM, May 8, 2000  [replies:3]
Jun Inamori has written a class called org.apache.tomcat.request.ParseMime which is available in the Tomcat CVS tree.

Jason Hunter has written a class called com.oreilly.servlet.MultipartRequest available on Servlets.com



Is this item helpful?  yes  no     Previous votes   Yes: 2  No: 0



Reply to this answer/comment  Help  

Re: Jun Inamori has written a class called org.apache....
Turgut Z. Yesilyurt, Jul 27, 2001
Hi, Could you please tell me what to do after I download his package and before create instance of MultipartRequest. I download it and put in my class path but the compiler does not find it.
Many thanks.
Turgut

Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  
Re: Jun Inamori has written a class called org.apache....
Arnaud Palazzi, Nov 29, 2002  [replies:1]
Hi,

Could someone show me some code examples really working with the com.oreilly.servlet.MultipartRequest?
I have built an applet to download scanned files from a client machine to a server.
I use the java class MultipartRequest in a servlet on my application server. It works fine with an HTML page sending a form with a type 'File' button using method POST .
In my applet, I use the class HttpMessage with the method InputStream sendPostMessage(java.io.Serializable obj)passing in the File to send. It sends some data but the servlet fails in decodind the multipart/form_data htpp message because of no boundary.
Can anyone help with telling me what I have to do or providing an example of uploading a single file from an applet to a servlet.

Thanks

Arnaud Palazzi

Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  
Question
Olga Narvaez, Mar 3, 2003
Hi Arnaud, I have to uploading a single file from an applet to a servlet. Did you do it? could you explain it to me? Kind Regards, Olga N.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 1



Reply to this answer/comment  Help  
I complie and run the Jason Hunter's MultipartRequest,...
Zuofeng Zeng, Nov 16, 2000  [replies:3]
I complie and run the Jason Hunter's MultipartRequest, but it can not write local system for uploaded file. How do? [Use java.io.FileOutputStream et al.

You may need to pass in the location of the "incoming" directory as a servlet initialization parameter.

-Alex]

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  

Re: I complie and run the Jason Hunter's MultipartRequest,...
Hong Cao, May 24, 2001  [replies:1]
Try this:
multi = new MultipartRequest(request, dirName, 10*1024*1024); // 10MB

if(submitButton.equals(multi.getParameter("Submit")))
{
    out.println("Files:");
    Enumeration files = multi.getFileNames();
    while (files.hasMoreElements()) {
	String name = (String)files.nextElement();
	String filename = multi.getFilesystemName(name);
	String type = multi.getContentType(name);
	File f = multi.getFile(name);
	FileReader fs = new FileReader(f);
	BufferedReader in = new BufferedReader(fs);
	String s, s2 = new String();
	while((s = in.readLine())!= null) {
	    s2 += s + "\n";
	}
	fileContent = s2;
	//session.setAttribute("fileContent", fileContent);
	//out.println(in.readLine());
	out.println("name: " + name);
	out.println("filename: " + filename);
	out.println("type: " + type);
	if (f != null) {
	    out.println("f.toString(): " + f.toString());
	    out.println("f.getName(): " + f.getName());
	    out.println("f.exists(): " + f.exists());
	    out.println("f.length(): " + f.length());
	    out.println("fileContent: " + fileContent);
	}
	in.close();
    }
}


Is this item helpful?  yes  no     Previous votes   Yes: 4  No: 1



Reply to this answer/comment  Help  
Re[2]: I complie and run the Jason Hunter's MultipartRequest,...
Alexander Greco, Mar 27, 2003
I would really like to know what needs to be passed to the request parameter: multi = new MultipartRequest(request, dirName, 10*1024*1024); // 10MB I would assume that dirName is the path where the file rests on the client machine but what is request? PLEASE HELP ME, I am totally confused

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: I complie and run the Jason Hunter's MultipartRequest,...
James Shipley, Sep 19, 2001
Is there a way to set the destination directory (i.e. where to save the file on the server) dynamically, instead of with a 'static' init value?

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
I recently re-implemented Jason's MultipartRequest...
Geoff Soutter, Nov 29, 2000
I recently re-implemented Jason's MultipartRequest - that class is now a thin wrapper around a new class called MultipartRequest. This new class allows one to get at the data without buffering it or writing it to disk. It also has fixes to avoid performance problems associated with poorly implemented servlet containers. I donated it back to Jason in honour of the service he has provided the java/servlet community and he has uploaded it onto servlets.com; so feel free to check it out.

Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  
Geoff, I am very interested in what you have done but...
Ian Davies, Dec 1, 2000  [replies:1]
Geoff, I am very interested in what you have done but I cannot find it on servlets.com. Can you be more specific as to its whereabouts?

Thanks.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: Geoff, I am very interested in what you have done but...
Geoff Soutter, May 3, 2001
Er whoops. I should have said "a new class MutipartParser" above. Anyway, check out these JavaDoc links to Jasons site: Heres the new MultipartParser class. It allows you to read FileParts which have a writeTo(File) and writeTo(OutputStream) method

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
The free class files from JSPSmart are the easiest...
Iain Delaney, Dec 15, 2000  [replies:12]
The free class files from JSPSmart are the easiest way to go, their sample pages work fine and are simple to figure out. Why is their site written in ASP though? :)

Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  
Re: The free class files from JSPSmart are the easiest...
zong zhang, Sep 17, 2001  [replies:1]
Hi Iain,
I am interested in the JspSmart as you mentioned. But i just want to up load file to Web server using servlet, not Jsp, can I still use JspSmart?
If I can, beside web Server like IIS and Jsp engine, what else do I need?
I am a beginner, I am a bit confused, is JSP a component of java SDK? do I need to download Jsp as well?

Is this item helpful?  yes  no     Previous votes   Yes: 1  No: 0



Reply to this answer/comment  Help  
Re: Re: The free class files from JSPSmart are the easiest...
Iain Delaney, Sep 18, 2001
I'm not sure why you would want to use a servlet and not JSP, because they are really the same thing. A JSP source file compiles into a servlet, so you get the same result in the end.
That said, all you need is a web server and a JSP engine, and all App Servers are JSP servers. There are also some free JSP servers about.
You don't need to download anything else, since the JSP server and the Java SDK will do all of the work. There are some good introductions to JSP on this site, on the Sun Java site, and there are a number of good books available now, too.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: The free class files from JSPSmart are the easiest...
Asar Khan, Sep 24, 2001  [replies:9]
Hi, I've just started using these classes and I cannot get them to work as a JSP although it does work as a servlet.

Here is my code as a jsp:

<%@ page import="com.jspsmart.upload.*" %>
<jsp:useBean id="ff" class="com.jspsmart.upload.SmartUpload" scope="page" />
<%
	String[] dir = { "C:\\temp\\tip.portal\\","/dp6.2/tip.portal/" };
	String   fn  = request.getParameter("filename");
	String   cn  = request.getParameter("clientno");
	int      id  = -1;


	if ( request.getServerName().equalsIgnoreCase("localhost") ) {
		id = 0;
	}
	else {
		id = 1;
	}

	String fid = dir[id] + cn + java.io.File.separator + fn;

	System.err.println(fid);

	try {
		ff.initialize( pageContext );
		ff.downloadFile( fid,"application/pdf" );
	}
	catch ( java.io.IOException e ) {
		if ( e instanceof java.io.FileNotFoundException ) {
			response.sendRedirect("\tip\file_not_found.html");
		}
		else {
			throw e;
		}
	}
	catch ( Exception e ) {
		e.printStackTrace(System.err);
		throw e;
	}
%>

This gives an error:

2001-09-24 17:18:06 - Ctx( /tip ): IllegalStateException in: R( /tip + /client/docs/view.jsp + null) 
OutputStream is already being used for this request

As a servlet:

package tip;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.jspsmart.upload.*;

public class viewClientSiteDocs extends TipServlet{

	private String[] TARGET_DIR = { "C:\\TEMP\\tip.portal\\","/dp6.2/tip.portal/" };

	private ServletConfig config;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.config = config;
	}

	public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException {
		doGet(req,res);
	}

	public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException {
		String clientno = req.getParameter("clientno");
		String filename = req.getParameter("filename");
		int i = ( req.getServerName().equalsIgnoreCase("localhost") ) ? 0 : 1;
		SmartUpload ff = new SmartUpload();
		try {
			String fid = TARGET_DIR[i] + clientno + java.io.File.separator + filename;
			ff.initialize( config,req,res );
			ff.setForcePhysicalPath(true);
			ff.downloadFile(fid,"application/pdf");
		}
		catch ( SmartUploadException e ) {
			e.printStackTrace(System.err);
		}
		catch ( IOException e ) {
			if ( e instanceof java.io.FileNotFoundException ) {
				try {
					res.sendRedirect("/tip/file_not_found.html");
				}
				catch ( IOException ex ) {
					ex.printStackTrace(System.err);
				}
			}
			else {
				e.printStackTrace(System.err);
			}
		}
		catch ( Exception e ) {
			e.printStackTrace(System.err);
		}
	}
}

It works.

Any ideas ???

Is this item helpful?  yes  no     Previous votes   Yes: 2  No: 1



Reply to this answer/comment  Help  

Re[2]: The free class files from JSPSmart are the easiest...
Jim Alexander, Feb 6, 2002  [replies:5]
I also had a problem with using jspSmartUpload to download a file... The same dang IllegalStateException.

But the servlet mechanism works great. I'm sticking with this approach.

Thanks very very much for your posting!

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  

Re[3]: The free class files from JSPSmart are the easiest...
Heather Elich, Apr 11, 2002
Does your servlet upload work for all file types, such as Word and Excel documents?

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[3]: The free class files from JSPSmart are the easiest...
piski pai, May 6, 2002
There is cheap and good component,may be this help. http://www.codecadet.com/components/ComponentDetail.aspx?ComponentID=Xqmwa46KLeY=

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[3]: The free class files from JSPSmart are the easiest...
Ken Kong, Aug 21, 2002  [replies:2]
I used the smartupload's download method and it work well for me and able to download many types of files (.doc, .ppt, .jpg ... etc) However, when I tried to download a certificate (.crt), the "illegalStateException: outputstream has been used.." error message resulted. I am aware of that tomcat will print an empty line in JSP tag. But I just don't know why it works for certain files only. Any idea?

Thks.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[4]: The free class files from JSPSmart are the easiest...
ravish gossain, Apr 12, 2006  [replies:1]
Dis error results because there are only a few content type specified by default in java.... like u will not be able to load .png files as multipart\png definition is not dere by default.....

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
« previous beginning next »


Ask A Question



 
Related Links

JSP FAQ

JSP Forum

Sun's JSP home page

SUN's JSP-Interest mailing archive

IBM's "Introduction to JSP" online course

JSP Insider

Servlets FAQ

Servlets Forum

Servlet-related resource list from Purple Technology

jGuru JSP FAQ

Sun Servlet Home Page

java.isavvix.com

Wish List
Features
About jGuru
Contact Us

 



The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers