This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes JSP and the fly likes File upload doesn't work when additional form elements introduced Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "File upload doesn Watch "File upload doesn New topic
Author

File upload doesn't work when additional form elements introduced

Annemarie McKeown
Ranch Hand

Joined: Nov 07, 2003
Posts: 47
I have a fileupload.html which requires input from user the following form elements:
title of file type(text), type (select option) and attachment which is a input type file and a submit button calling action to upload.jsp.
The upload.jsp completely handles the upload of the file.
The upload works successfully, if I remove the two form elements text and select from fileupload.html, but if I put them in it doesn't - upload.jsp returns an exception - Problem File Creation which is reference by - FNF see snippet of code for details.
I have copied my complete upload.jsp below. I simply have an input type=file on my fileupload.html and when I add two other form elements input type = text name = project_title and select_name=project_type the upload.jsp doesn't work.
Could someone try and tell me why and and what I need to change in my upload.jsp?
--------------------------------------------------------------------------
<%@ page errorPage="error.jsp" %>
<jsp:useBean id="prop" scope="page" class="java.util.Properties" />
<%@ page language="java" import="java.io.*,java.util.*,javax.servlet.*" %>
<%
String projectTitle = request.getParameter("project_title");
String projectType = request.getParameter("project_type");
%>

<%!
public String getBoundary(HttpServletRequest request,Properties prop) throws ServletException,IOException{
String boundary = null;
Enumeration enum = request.getHeaderNames();
while(enum.hasMoreElements()){
String header = (String)enum.nextElement();
String hvalue = request.getHeader(header);
prop.setProperty((header).toLowerCase(),hvalue);
if( "content-type".equalsIgnoreCase(header) ){
int idx = hvalue.lastIndexOf("boundary=");
if( idx != -1 ){
boundary= hvalue.substring( idx+9 , hvalue.length());
}
}
}
return boundary;
}
public String getFileName(String secondline){
int len = secondline.length();
int idx = secondline.lastIndexOf("filename=");
if( idx == -1 ) return null;
String filename = secondline.substring( idx+10 , len-1);
filename = filename.replace('\\','/');
idx = filename.lastIndexOf("/");
idx = idx + 1;
filename = filename.substring( idx );
return filename;
}
%>
<%
//fetch path dynamically to upload files to server.
String DPATH = application.getRealPath("//uploads//");
int ROUGHSIZE=1024;
int MAXSIZE = 10; // Mega Byte
String boundary = getBoundary(request,prop);
if( boundary == null ){
boundary = prop.getProperty("boundary");
}else{
boundary = "--"+boundary;
}
if( boundary == null ){
throw new Exception("BNF");
}
Long contentsize = new Long(prop.getProperty("content-length","0"));
int c;
StringWriter st = new StringWriter();
if( contentsize.longValue() < 1L ){
throw new Exception("ZERO");
}
long l = contentsize.longValue() - ROUGHSIZE;

int KB = 1024;
int MB = 1024 * KB;
int csize = (int)(l / MB);
if( csize > MAXSIZE ){
throw new Exception("EL");
}
ServletInputStream fin = request.getInputStream();
//Getting Start Boundary Line
int cn;
int count=0;
while( (c=fin.read()) != -1 ){
if( c == '\r') break;
st.write(c);
count++;
}
c=fin.read();//read new line
String tboundary = st.getBuffer().toString();
tboundary=tboundary.trim();
if( ! tboundary.equalsIgnoreCase( boundary) ){
throw new Exception("BBNF");
}
st.close();
st = null;
st = new StringWriter();
//Getting File Information
while( (c=fin.read()) != -1 ){
if( c == '\r' ) break;
st.write(c);
}
c=fin.read();//read new line
String secondline = st.getBuffer().toString();
String filename = getFileName(secondline);
st.close();
st = null;
st = new StringWriter();
//Read Content Type of File
while( (c=fin.read()) != -1 ){
if( c == '\r' ) break;
st.write( c );
}
c=fin.read();//read new line
//out.println( st.getBuffer().toString() );
//Read \r and \n character
fin.read();
fin.read();
File newfile = null;
FileOutputStream fout =null;
try{
if( filename == null ) throw new FileNotFoundException("File Name not found");
newfile = new File(DPATH+filename);
fout = new FileOutputStream( newfile );
}catch(FileNotFoundException fnexp){
fin.close();
throw new Exception("FNF");
}

byte b[] = null;
while( l > 1024L ){
b = new byte[1024];
fin.read(b,0,1024);
fout.write(b);
b=null;
l -= 1024L;
}
if( l > 0 ){
b = new byte[(int)l];
fin.read(b,0,(int)l);
fout.write(b);
}

ByteArrayOutputStream baos = new ByteArrayOutputStream();
while( (c = fin.read()) != -1 ){
baos.write(c);
}
String laststring = baos.toString();
int idx = laststring.indexOf(boundary);
b = baos.toByteArray();
if( idx > 2 ){
fout.write(b,0,idx-2);
}else
{
fout.close();
newfile.delete();
throw new Exception("EBNF");
}
fout.flush();
fout.close();
fin.close();


String filenametmp = newfile.getName();
String location = DPATH + filenametmp;

%>
<html>
<body>
<TABLE>
<TR>
<TD>FileName</TD><TD><%=newfile.getName()%></TD>
</TR>
<TR>
<TD>FileSize</TD><TD><%=newfile.length()%></TD>
</TR>
<TD>Location</TD><TD><a href="<%=location%>">Download</a></TD>
</TR>
</TABLE>
<%out.println(projectTitle);%>
</body>
</html>
[ February 24, 2004: Message edited by: Annemarie McKeown ]
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60774
    
  65

What is the enctype of the form submitting the upload?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Shane Lilly
Greenhorn

Joined: Feb 20, 2004
Posts: 18
Yeah if you can provide more info on the enctype of the form submitting the upload I might be able to help!
Annemarie McKeown
Ranch Hand

Joined: Nov 07, 2003
Posts: 47
Sorry, I am using multipart/form-data
<form name="Test" method="post" action="upload.jsp" enctype="multipart/form-data">

Let me know if you can help please.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60774
    
  65

Here a few suggestions that might help us help you out:
1) Post the stack trace (or at least the most important portion of it) so we can see the exact nature of the error you are getting. Be sure to use the UBB code tags to preserve the formatting of the stack trace.
2) Edit your original post to use the UBB code tags around your code in order to preserve its original formatting. No one wants to spend time reading a large batch of unformatted code.
3) I'd also post the HTML code for the multi-part form (code tagged, of course) in case there are any clues there.
Yuriy Fuksenko
Ranch Hand

Joined: Feb 02, 2001
Posts: 413
There is a nice article
http://www.fawcette.com/javapro/2002%5F01/magazine/features/acalsavara/default.aspx
This article also contains a source code, wich might help you.
http://www.fawcette.com/javapro/code/2002_01/jp0201ac.zip
I used a class provided, and did not have any problems.
[ February 25, 2004: Message edited by: Yuriy Fuksenko ]
Annemarie McKeown
Ranch Hand

Joined: Nov 07, 2003
Posts: 47
I don't get a stack trace or anything in my console window where tomcat was started from.
When I include the code to introduce new form elements along with the file upload element the upload.jsp (process page) just displays the following text -
Please Select File / Problem in File Creation
which references part of upload.jsp....
try{
if( filename == null ) throw new FileNotFoundException("File Name not found");
newfile = new File(DPATH+filename);
fout = new FileOutputStream( newfile );
}catch(FileNotFoundException fnexp){
fin.close();
throw new Exception("FNF");
}
Contents of exception FNF are stored in error.jsp
}
else if(exception.getMessage().equals("FNF") ){
out.println("Please select file / Problem in File Creation");
}
I have include my html code here maybe you can see why addding these two form elements my file upload doesn't work at all, and when I take them out it does. Seems like upload.jsp doesn't even see that the user has selected a file for attachment - for some bizarre reason. Maybe you can help..please..
fileupload.html
---------------
<html>
<head><title>Test</title></head>
<body>
<form name="Test" method="post" action="upload.jsp" enctype="multipart/form-data">
<table width="35%" height="40%" border="0" cellspacing="3" cellpadding="5" align="left" bgcolor="#CCCCCC">
<tr>
<td><font size="2">Project Title: <input type="text" name="project_title" size="20"></td>
</tr>
<tr>
<td><font size="2">Project Type: <select name="project_type">
<option value=null>Please select</option>
<option value="course_notes">Course Notes</option>
<option value="assignment">Assignments</option>
</select></td>
</tr>
<tr><td><font size="2">Attachment :</font>
<input type="File" name="file" >

</td>
</tr>
<tr>
<td align=center>

<input type="Submit" value="Upload File" name="Submit" >

</td>
</tr>
</table>
</form>
</body>
</html>
 
Don't get me started about those stupid light bulbs.
 
subject: File upload doesn't work when additional form elements introduced
 
Similar Threads
File Upload
error in dwonloading a pdf file
upload file in jsp
How to import CSV file into Mysql using jsp
File upload only handles .txt documents??