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 &quot;file&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
 |
 |
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
|
|

|
 |
 |
 |
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
|
|

|
 |
 |
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
|
|

|
 |
 |
 |
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
|
|

|
 |
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
|
|

|
 |
 |
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
|
|

|
 |
 |
 |
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
|
|

|
 |
 |
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
|
|

|
 |
 |
 |
 |
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
|
|

|
|
|
 |
|