This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Servlets and the fly likes file uploading using enctype= Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "file uploading using enctype="MULTIPART/FORM-DATA" " Watch "file uploading using enctype="MULTIPART/FORM-DATA" " New topic
Author

file uploading using enctype="MULTIPART/FORM-DATA"

alok kaushik
Greenhorn

Joined: Aug 08, 2001
Posts: 5
hello all,
i m doing file uploading using jsp, i have a jsp file in which i am making a form for posting data to the server. i m using the <form enctype="MULTIPART/FORM-DATA" action=abc.jsp" method=post>
in jsp file.. i and when i post this data to the my process jsp file... values of html fields goes null... if i don't use this enctype="MULTIPART/FORM-DATA" in form tag in my jsp file and post data to server file where my process jsp file do the work of data storing and file uploading it gives the error when it uploads the file. please help me regarding this .........
alok
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
You can use the search facilityu in this forum This has been discussed several times.

Bosun


Bosun (SCJP, SCWCD)
So much trouble in the world -- Bob Marley
daman sidhu
Ranch Hand

Joined: Aug 19, 2000
Posts: 184
Hi,
For this problem you can use the oriellys class which can be downloaded from their site or it is also in the servlets book by orielly, you will be able to get both the uploaded files as well as the normal html form fields thru that.
Or rather ill paste it here, just pass the request object, the directory where u need the uploaded file to the class MultipartRequestHandler and use getParameter and getFile to get the files.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MultipartRequest {
private static final int DEFAULT_MAX_POST_SIZE = 1024 * 1024; // 1 Meg
private ServletRequest req ;
private File dir;
private int maxSize;
private Hashtable parameters = new Hashtable(); // name - Vector of values
private Hashtable files = new Hashtable(); // name - UploadedFile

/**
* Constructs a new MultipartRequest to handle the specified request,
* saving any uploaded files to the given directory, and limiting the
* upload size to 1 Megabyte. If the content is too large, an
* IOException is thrown. This constructor actually parses the
* <tt>multipart/form-data</tt> and throws an IOException if there's any
* problem reading or parsing the request.
*
* @param request the servlet request.
* @param saveDirectory the directory in which to save any uploaded files.
* @exception IOException if the uploaded content is larger than 1 Megabyte
* or there's a problem reading or parsing the request.
*/
public MultipartRequest(ServletRequest request,String saveDirectory) throws IOException
{
this(request, saveDirectory, DEFAULT_MAX_POST_SIZE);
}
/**
* Constructs a new MultipartRequest to handle the specified request,
* saving any uploaded files to the given directory, and limiting the
* upload size to the specified length. If the content is too large, an
* IOException is thrown. This constructor actually parses the
* <tt>multipart/form-data</tt> and throws an IOException if there's any
* problem reading or parsing the request.
*
* @param request the servlet request.
* @param saveDirectory the directory in which to save any uploaded files.
* @param maxPostSize the maximum size of the POST content.
* @exception IOException if the uploaded content is larger than
* <tt>maxPostSize</tt> or there's a problem reading or parsing the request.
*/
public MultipartRequest(ServletRequest request,String saveDirectory,int maxPostSize) throws IOException
{
// Sanity check values
if (request == null)
throw new IllegalArgumentException("request cannot be null");
if (saveDirectory == null)
throw new IllegalArgumentException("saveDirectory cannot be null");
if (maxPostSize <= 0)
throw new IllegalArgumentException("maxPostSize must be positive");
// Save the dir
req = request;
dir = new File(saveDirectory);
maxSize = maxPostSize;
// Check saveDirectory is truly a directory
if (!dir.isDirectory())
throw new IllegalArgumentException("Not a directory: " + saveDirectory);
// Check saveDirectory is writable
if (!dir.canWrite())
throw new IllegalArgumentException("Not writable: " + saveDirectory);
readRequest();
}
private String extractBoundary(String line)
{
int index = line.indexOf("boundary=");
if(index == -1)
{
return null;
}
String boundary = line.substring(index+9);
boundary = "--"+boundary;
return boundary;
}
private String extractContentType(String line) throws IOException
{
String contentType = null;
String origline =line;
line = origline.toLowerCase();
if(line.startsWith("content-type"))
{
int start = line.indexOf(" ");
if(start ==-1)
{
throw new IOException("Content Type Corrupt : "+origline);
}
contentType = line.substring(start+1);
}
else if(line.length() !=0)
{
throw new IOException("Malformed line after disposition :"+origline);
}
return contentType;
}
private String[] extractDispositionInfo(String line) throws IOException
{
String[] retval = new String[3];
String origline = line;
line = origline.toLowerCase();
int start = line.indexOf("content-disposition:");
int end = line.indexOf(";");
if(start == -1 | | end == -1)
{
throw new IOException("Content Disposition corrupt :"+origline);
}
String disposition = line.substring(start+21,end);
if(!disposition.equals("form-data"))
{
throw new IOException("Invalid Content Disposition : "+disposition);
}
start = line.indexOf("name=\"",end);
end = line.indexOf("\"",start +7);
if(start ==-1 | | end == -1)
{
throw new IOException("Content Disposition corrupt :"+origline);
}
String name = origline.substring(start+6,end);
String filename = null;
start = line.indexOf("filename=\"",end+2);
end = line.indexOf("\"",start+10);
if(start != -1 && end!=-1)
{
filename = origline.substring(start+10,end);
int slash = Math.max(filename.lastIndexOf('/'),filename.lastIndexOf('\\'));
if(slash > -1)
{
filename= filename.substring(slash+1);
}
if(filename.equals(""))
{
filename= "unknown";
}
}
retval[0] = disposition;
retval[1] = name;
retval[2] = filename;
return retval;
}
/**
* Returns the content type of the specified file (as supplied by the
* client browser), or null if the file was not included in the upload.
*
* @param name the file name.
* @return the content type of the file.
*/
public String getContentType(String name) {
try {
UploadedFile file = (UploadedFile)files.get(name);
return file.getContentType(); // may be null
}
catch (Exception e) {
return null;
}
}
/**
* Returns a File object for the specified file saved on the server's
* filesystem, or null if the file was not included in the upload.
*
* @param name the file name.
* @return a File object for the named file.
*/
public File getFile(String name)
{
try
{
UploadedFile file = (UploadedFile)files.get(name);
return file.getFile(); // may be null
}
catch (Exception e) {
return null;
}
}
/**
* Returns the names of all the uploaded files as an Enumeration of
* Strings. It returns an empty Enumeration if there are no uploaded
* files. Each file name is the name specified by the form, not by
* the user.
*
* @return the names of all the uploaded files as an Enumeration of Strings.
*/
public Enumeration getFileNames()
{
return files.keys();
}
/**
* Returns the filesystem name of the specified file, or null if the
* file was not included in the upload. A filesystem name is the name
* specified by the user. It is also the name under which the file is
* actually saved.
*
* @param name the file name.
* @return the filesystem name of the file.
*/
public String getFilesystemName(String name)
{
try
{
UploadedFile file = (UploadedFile)files.get(name);
return file.getFilesystemName(); // may be null
}
catch (Exception e) {
return null;
}
}
/**
* Returns the value of the named parameter as a String, or null if
* the parameter was not sent or was sent without a value. The value
* is guaranteed to be in its normal, decoded form. If the parameter
* has multiple values, only the last one is returned (for backward
* compatibility). For parameters with multiple values, it's possible
* the last "value" may be null.
*
* @param name the parameter name.
* @return the parameter value.
*/
public String getParameter(String name)
{
try
{
String param = (String)parameters.get(name);
if(param.equals(""))
return null;
return param;
}
catch (Exception e)
{
return null;
}
}
/**
* Returns the names of all the parameters as an Enumeration of
* Strings. It returns an empty Enumeration if there are no parameters.
*
* @return the names of all the parameters as an Enumeration of Strings.
*/
public Enumeration getParameterNames()
{
return parameters.keys();
}
/**
* Returns the values of the named parameter as a String array, or null if
* the parameter was not sent. The array has one entry for each parameter
* field sent. If any field was sent without a value that entry is stored
* in the array as a null. The values are guaranteed to be in their
* normal, decoded form. A single value is returned as a one-element array.
*
* @param name the parameter name.
* @return the parameter values.
*/
public String[] getParameterValues(String name) {
try {
Vector values = (Vector)parameters.get(name);
if (values == null | | values.size() == 0) {
return null;
}
String[] valuesArray = new String[values.size()];
values.copyInto(valuesArray);
return valuesArray;
}
catch (Exception e) {
return null;
}
}
protected void readAndSaveFile(MultipartInputStreamHandler in, String boundary,String filename) throws IOException
{
File f = new File(dir+File.separator+filename);
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream out = new BufferedOutputStream(fos,8*1024);
byte []bbuf = new byte[8*1024];
int result;
String line;
boolean rnflag = false;
while((result=in.readLine(bbuf,0,bbuf.length))!=-1)
{
if(result > 2 && bbuf[0] == '-' && bbuf[1] == '-')
{
line = new String(bbuf,0,result,"ISO-8859-1");
if(line.startsWith(boundary))
{
break;
}
}
if(rnflag)
{
out.write('\r');
out.write('\n');
rnflag= false;
}
if(result >=2 && bbuf[result-2] =='\r' && bbuf[result-1] =='\n')
{
out.write(bbuf,0,result-2);
rnflag = false;
}
else
{
out.write(bbuf,0,result);
}
}
out.flush();
out.close();
fos.close();
}
protected boolean readNextPart(MultipartInputStreamHandler in,String boundary) throws IOException
{
String line = in.readLine();
if(line==null)
{
return true;
}
String []dispInfo = extractDispositionInfo(line);
String disposition = dispInfo[0];
String name = dispInfo[1];
String filename = dispInfo[2];
line = in.readLine();
if(line == null)
{
return true;
}
String contentType = extractContentType(line);
if(contentType != null)
{
line = in.readLine();
if(line == null | | line.length() > 0)
{
throw new IOException("Malformed Line After Content Type "+line);
}
}
else
{
contentType = "application/octet-stream";
}
if(filename == null)
{
String value = readParameter(in,boundary);
parameters.put(name,value);
}
else
{
readAndSaveFile(in,boundary,filename);
if(filename.equals("unknown"))
{
files.put(name,new UploadedFile(null,null,null));
}
else
{
files.put(name,new UploadedFile(dir.toString(),filename,contentType));
}
}
return false;
}
protected String readParameter(MultipartInputStreamHandler in, String boundary) throws IOException
{
StringBuffer sbuf = new StringBuffer();
String line;
while((line = in.readLine()) != null)
{
if(line.startsWith(boundary))
{
break;
}
sbuf.append(line+"\r\n");
}
if(sbuf.length() == 0)
{
return null;
}
sbuf.setLength(sbuf.length() -2);
return sbuf.toString();
}
protected void readRequest() throws IOException
{
String type = req.getContentType();
if(type==null | | !type.toLowerCase().startsWith("multipart/form-data"))
{
throw new IOException("Posted Content Type Isn't maultipart/form-data");
}
int length = req.getContentLength();
if(length>maxSize)
{
throw new IOException("Posted Content Length of "+length+" exceeds limit of "+maxSize);
}
String boundary = extractBoundary(type);
if(boundary == null)
{
throw new IOException("Separation boundary was not specified");
}
MultipartInputStreamHandler in = new MultipartInputStreamHandler(req.getInputStream(),boundary,length);
String line = in.readLine();
if(line==null)
{
throw new IOException("Corrupt form data: premature ending");
}
if(!line.startsWith(boundary))
{
throw new IOException("Corrupt form data: no leading boundary");
}
boolean done = false;
while(!done)
{
done = readNextPart(in,boundary);
}
}
}
*********************
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
class MultipartInputStreamHandler
{
ServletInputStream in;
String boundary;
int totalExpected;
int totalRead = 0;
byte[] buf = new byte[8*1024];
public MultipartInputStreamHandler(ServletInputStream in, String boundary,int totalExpected)
{
this.in = in;
this.boundary = boundary;
this.totalExpected =totalExpected;
}
public String readLine() throws IOException
{
StringBuffer sbuf = new StringBuffer();
int result;
String line ;
do
{
result= this.readLine(buf,0,buf.length);
if(result !=-1)
{
sbuf.append(new String(buf,0,result,"ISO-8859-1"));
}
}while(result == buf.length);
if(sbuf.length() == 0)
{
return null;
}
sbuf.setLength(sbuf.length()-2);
return sbuf.toString();
}
public int readLine(byte b[],int off,int len) throws IOException
{
if(totalRead>=totalExpected)
return -1;
else
{
int result=in.readLine(b,off,len);
if(result>0)
{
totalRead+=result;
}
return result;
}
}
}
*****************
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
// A class to hold information about an uploaded file.
//
class UploadedFile
{
private String dir;
private String filename;
private String type;
UploadedFile(String dir, String filename, String type)
{
this.dir = dir;
this.filename = filename;
this.type = type;
}
public String getContentType()
{
return type;
}
public File getFile()
{
if (dir == null | | filename == null)
{
return null;
}
else
{
return new File(dir + File.separator + filename);
}
}
public String getFilesystemName()
{
return filename;
}
}
**************************
the sample of how to read it is::
MultipartRequest multi=new MultipartRequest(request,".",5*1024*1024);
Enumeration files=multi.getFileNames();
while(files.hasMoreElements())
{
String name=(String)files.nextElement();
String filename=multi.getFilesystemName(name);
String type=multi.getContentType(name);
f=multi.getFile(name);
}
String myParam=multi.getParameter("myPassesParam");
Cheers.
Daman
daman sidhu
Ranch Hand

Joined: Aug 19, 2000
Posts: 184
While we are at it, i do have a query that i have already posted in another post is that i want the length and the height of the image that is being uploaded to be determined.Does anyone know how to do this in servlet, because what we do for applets donot work here.

Daman
Vlad Patryshev
Ranch Hand

Joined: Jun 30, 2001
Posts: 61
I am sure that to do this, you have to open the image file and use the knowledge of the file format to find out its size.


Thanks,<br />Vlad
alok kaushik
Greenhorn

Joined: Aug 08, 2001
Posts: 5
thx for providing me this information
i got the solution but still i m facing problems tht i m getting values of all fields using MultipartRequest.getParameter() and values are also goin in database but file which is i m uploading is not goin in the directory, which patht i m giving in MultipartRequest constructor.....
pls help me regarding this
alok
 
 
subject: file uploading using enctype="MULTIPART/FORM-DATA"