Interruption file upload breaks servlet engine...
Hi,
I've written a file upload servlet, which works great, until someone abandons an upload half way through the process. My servlet seems to block open a port or process, and cause my jsp pages to stop responding!!! resulting in breaking my site. I have to manually kill the servlet engine, and restart the process. The JSP engine is tomcat 4.1.27. Any ideas on preventing the system locking up, or where i can look for clues as to what is actually happening would be greatly appreciated.
TIA
Steve
You'll have to debug it - for example, sprinkle System.out.println("now I'm here in the code") statements, and reproduce the scenario by invoking it yourself and aborting the upload. It should throw an exception while you're reading the upload stream - maybe you're not handling that correctly.
Similar Messages
-
I am a new servlet programmer.......
iam using tomcat server......
can any one pls help in writing code for file upload using servlets and jsp without using multipart class or any other class like that....
Please URGENT..Slow down! "Urgent" is from your perspective alone. I, myself, am not troubled or worried in the least.
hi ugniss
thanks for ur reply....sorry i was not
y i was not asked not to use multipart class or any
other class like that...is there any other
possibility to do file uploading from jsp to
servlet...
Just as an aside, a JSP is a Servlet. But even if I move beyond that, the question does not make sense. If you want a "JSP to upload to a Servlet", then simply do so in memory. You are still (likely) within the same scope of a given request. However, if instead you are referring to a JSP that is displayed on a browser, then really you are talking about HTML, which is what the browser will receive. And since you are now talking about a browser, your only real, viable option is a multi-part file upload. So, it is either server or it is browser. And either way, the question leads to very established options, as outlined above.
the main concept is.. in the browser the user selects
a particular file and clicks the button upload..after
clicking upload the jsp should sent the file to the
servlet in streams...there the servlet gets in and
saves in a server location........this is wat i hav
to do...
Okay. So, after reading my previous (redundant) paragraph, we have arrived at the crux of the issue. You have a JSP that will be output as HTML to a client (browser) which you want to upload content to your server (handled by a Servlet). So, you are now stuck again with multi-part. The requirement to not use multi-part is non-sensical. You can overcome it, say, if you write your own applet or standalone Swing client. However, if your users are invoking this functionality from a browser, you are limited by the options that W3C has provided you. Use multi-part.
is there aby possibilty to do this.....can any one
pls help....Take the advice to download and review Jakarta Commons FileUpload. Inform your management that their requirement makes no technical sense. Research on your own. There are dozens of examples (and tutorials) on file upload using multi-part. Embrace it. Live it. Love it.
- Saish -
File uploads using servlets to oracle8i database
Hi,
Help please, How I can a File Upload using BLOB's into the oracle database, any sugestions...
Thanks
Moacyr
[email protected]Try the jason hunter book Java Servlet Programming for a very good description or the web site hosted by o'reilly
www.servlets.com
Has a very neat java class for decoding multipart mime encoded files (the upload stream from the browser). Seems to accomodate most of the differing browsers intretation of the standard.
Note to Oracle: This should really be handled by the servlet engine as an Oracle extension. Where the servlet engine strips the mime encoding out before the servlet is called placing the decoded file in an associated extension call. ie: cast the request to an Oracle request object which has file uploaded method. -
File upload using Servlets and Weblogic
Hi,
I need to write a servlet that can upload a .doc file to a folder on the server. Can someone please let me know abot the code i need to write, as i am a novice in servlets.
Thanks in advance
buddy0303Another, simpler (we think), such package is Jenkov HTTP Multipart File Upload. It's a servlet filter which can work in front of both servlets and JSP's. The servlet filter parses the uploaded file and stores it temporarily on the servers disk. When the servlet or JSP executes afterwards, it can obtain all the information about the file, from the request attributes. There is a decent manual for HTTP Multipart File Upload on the website.
Just search for "Jenkov HTTP Multipart" on Google and you'll find it. HTTP Multipart is free, open source, Apache Licsense. -
Hi at all.
I need to upload file from a client flex application to the
application server.
If I don't use Flex this is a simple task made by a Servlet
that manage a form submit.
In Flex I found example that show how to do the same thing
but with the use of a ColdFusion script.
I can't use a solution like that beacuse my backend system is
made with J2EE and I've already developed a lot of servlets that
expose this functions.
Anyone know how to use FileReference and URLRequest to invoce
a Servlet for uploading files ?
Thank at allYes I believe that either the Jakarta Commons library or the O'Reilly package will actually take care of the file writing, all you need to do is tell it where.
-
1. when use com.oreilly.servlet.MultipartRequest to handle the file upload, can I change the upload file name .
2. how com.oreilly.servlet.MultipartReques handle file upload? do it change to byte ?
what different? if I use the following method?
File uploadedFile = (File) mp.getFile("filename");
FileOutputStream fos = new FileOutputStream(filename);
byte[] uploadedFileBuf = new byte[(int) uploadedFile.length()];
fos.write(data);
fos.close();My questions are
1) when use oreilly package to do file upload , it looks like i line of code is enough to store the upload file in the
file direction.
MultipartRequest multi =
new MultipartRequest(request, dirName, 10*1024*1024); // 10MB
why some example still use FileOutputStream?
outs = new FileOutputStream(UPLOADDIR+fileName);
filePart.writeTo(outs);
outs.flush();
outs.close();
2) can I rename the file name when I use oreilly package? -
HELP! File Upload Servlet and Internet Explorer
Hello people. I hope this is an easy problem to solve...
I have a servlet upload program that works using Mozilla browser (www.mozilla.org), but for some reason it doesn't work using Microsoft IE. The servlet is also using the servlet upload API from Apache (commons).
I'm using IE version 6.0.2800.1106 in a Win98SE host computer. I get a cannot find path specified error message (see below). At work, I also get the same error message using IE, but don't know what version. The OS is XP. Unfortunately, at work, I can't install Mozilla browser (or any software-company policy) to see if Mozilla works there too. I would've like to have tested to see if the upload program worked on Mozilla on a truly remote computer.
So I figured, it must be a IE configuration issue, but darn it!! I began by resetting IE to default settings, but still have the problem, I played around with several different combinations of settings in "Tools"-->"Internet Options...", and I still get the error message. Someone PLEASE HELP ME!!!
Dunno, if it will help, I've also pasted the upload servlet source code below and the html file that's calling the upload servlet, but you still need the Apache commons file upload API.
Trust me on this one folks, for some reason it works for Mozilla, but not for IE. With IE, I can at least access web server, and therefore, the html file that calls the upload servlet , so I don't think it's a Tomcat configuration issue (version 5.0). I actually got the code for the file upload servlet from a book relatively new in the market (printed in 2003), and it didn't mention any limitations as far as what browser to use or any browser configuration requirements. I have e-mailed the authors, but they probably get a ton of e-mails...
Anyone suggestions?
Meanwhile, I will try to install other free browsers and see if the file upload program works for them too.
ERROR MESSAGE:
"HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: C:\TOMCAT\webapps\MyWebApps\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:43)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
root cause
java.io.FileNotFoundException: C:\TOMCAT\webapps\MyWebApp\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
java.io.FileOutputStream.open(Native Method)
java.io.FileOutputStream.(FileOutputStream.java:176)
java.io.FileOutputStream.(FileOutputStream.java:131)
org.apache.commons.fileupload.DefaultFileItem.write(DefaultFileItem.java:392)
com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
note The full stack trace of the root cause is available in the Tomcat logs.
Apache Tomcat 5.0.16"
FILE UPLOAD SERVLET source code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import java.util.*;
public class FileUploadCommons extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.print("File upload success. <a href=\"/MyWebApp/files/");
out.print("\">Click here to browse through all uploaded ");
out.println("files.</a><br>");
ServletContext sc = getServletContext();
String path = sc.getRealPath("/files");
org.apache.commons.fileupload.DiskFileUpload fu = new
org.apache.commons.fileupload.DiskFileUpload();
fu.setSizeMax(-1);
fu.setRepositoryPath(path);
try {
List l = fu.parseRequest(request);
Iterator i = l.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem)i.next();
fi.write(new File(path, fi.getName()));
catch (Exception e) {
throw new ServletException(e);
out.println("</html>");
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
doPost(request, response);
HTML PAGE that calls the upload servlet:
<html>
<head>
<title>Example HTML Form</title>
</head>
<body>
<p>Select a file to upload or browse
currently uploaded files.</p>
<form action="http://##.##.##.####/MyWebApp/FileUploadCommons"
method="post" enctype="multipart/form-data">
File: <input type="file" name="file"><br>
<input value="Upload File" type="submit">
</form>
</body>
</html>
Thanks in advance for any assistance.
-DanI'm guessing what is happening is that Mozilla tells the servlet "here comes the file myfile.zip". The servlet builds a file name for it:
String path = sc.getRealPath("/files");
// path is now C:\TOMCAT\webapps\MyWebApps\files\
fi.write(new File(path, fi.getName()));
// append myfile.zip to "path", making it C:\TOMCAT\webapps\MyWebApps\files\myfile.zipIE, however, tells "here comes the file C:\WINDOWS\Desktop\myfile.zip". Now imagine what the path+filename ends up being...
So what you want to do is something along the lines of (assuming Windoze):
public static String basename(String filename)
int slash = filename.lastIndexOf("\\");
if (slash != -1)
filename = filename.substring(slash + 1);
// I think Windows doesn't like /'s either
int slash = filename.lastIndexOf("/");
if (slash != -1)
filename = filename.substring(slash + 1);
// In case the name is C:foo.txt
int slash = filename.lastIndexOf(":");
if (slash != -1)
filename = filename.substring(slash + 1);
return filename;
fi.write(new File(path, basename(fi.getName()));
....You can make the file name check more bomb proof if security is an issue. Long file names trying to overflow something in the OS, NUL characters, Unicode, forbidden names in Windos (con, nul, ...), missing file name, ... -
How to upload files through a servlet/jsp form?
anyone know basically how to do this?
i need to write a simple jsp form the can browse for a file on my machine, then upload it to a server in the usual html form manner.
is this done with an i/o stream?
thanks for any help!
robSmyth
[email protected]jspSmart has a free upload component you can use for HTTP file uploading. (http://www.jspsmart.com )
Also, O'Reilly has an open source package you can use. (http://www.oreilly.com or http://www.servlets.com )
Another option is dotJ, which has an upload tag in its tag library. Benefit of this library is that it has a much more compehensive set of JSP tags. (http://www.dotjonline.com ) -
File upload and download using jsp/servlets
How to upload any file to the server using jsp/servlets. . Help me out
You can also try the Jenkov HTTP Multipart File Upload. It's a servlet filter that is easy to add to your web-project. After adding it, you can access both request parameters and the uploaded files easily. It's more transparent than Apache Commons File Upload. There is sufficient documentation to get you started, and there is a forum if you have any questions.
Jenkov HTTP Multipart File Upload is available under the Apache license, meaning its free to use. -
Name of uploaded file (BLOB) in Servlet
Hi,
I'm trying to save into DB any file I want throw servlet via POST request.
Is there any way how to get the name of uploaded file from posted information (from posted file).
Then I save this file as BLOB into DB.
Can you help me with getting the file name???
Because I would like to save the name also into DB...
Thanks JanJason Hunter of Servlet fame and fortune has had a general servlet framework extension available for quite a while now. This has code which supports many common operations, including handling multipart-file upload.
See http://www.servlets.com/cos/index.html#classes and more specifically http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartRequest.html
The code is available, so you should be able to take a peek and see how he handles this issue, as an example.
cheers
-steve- -
Servlet file uploading code need.
Hello
Can somebody give me a sourcecode of working servlet program that do file uploading on the server?
thnksHe's not angry at you, he's just angry at the self-serving tone of your post.
Why don't you give me a $100 USD... while at it? Oh, no? But WHY? Why oh why? I'm such a good person of liberal character - could you give me a 100 dollars RIGHT NOW? Oh, you wouldn't - I see...
Almost the same w/that "give me source code" :).... -
Java.io.IOException in servlet-based file upload
Hi,
I'm running into some problems with Weblogic Server 5.1 on Unix (Solaris), while
trying to do a servlet-based file upload. I'm trying to upload a file to the
server file system through a file upload servlet running inside Weblogic Server
5.1, and I get an exception when I try to create a file on the Unix server
filesystem:
java.io.IOException: Not owner
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:692)
at com.cysive.filemanagement.UploadFile.save(UploadFile.java:84)
I tried changing the upload location to various places, like directly in the
docroot (myserver/public_html), in my home directory, etc. I am not sure which
owner Weblogic is looking for, because the process is owned by whoever starts
the WL server. And the strange thing is, I am able to create new directories on
the file system, just not files.
When I run the exact code on WinNT, everything works fine... I am able to create
files and directories and the upload goes through smoothly.
I'm thinking there is something I need to be setting in the weblogic.properties
file on Unix by way of permissions/privileges that is not required on WinNT, but
was not able to find anything in the documentation.
Could anyone help, please?
Thanks.
Hrishi
Check what user/group you are running your weblogic server.(check out the user who starts as well as UID/user/group in weblogic.properties file if you have set them).
check out whether that user/group has necessary permission on unix m/c
Hrishi Dixit <[email protected]> wrote:
>
Hi,
I'm running into some problems with Weblogic Server on Unix, while trying to do
a servlet-based file upload. I'm trying to upload a file to the server file
system through a file upload servlet running inside Weblogic Server 5.1, and I
get an exception when I try to create a file on the Unix server filesystem:
java.io.IOException: Not owner
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:692)
at com.cysive.filemanagement.UploadFile.save(UploadFile.java:84)
I tried changing the upload location to various places, like directly in the
docroot (myserver/public_html), in my home directory, etc. I am not sure which
owner Weblogic is looking for, because the process is owned by whoever starts
the WL server. And the strange thing is, I am able to create new directories on
the file system, just not files.
When I run the exact code on WinNT, everything works fine... I am able to create
files and directories and the upload goes through smoothly.
I'm thinking there is something I need to be setting in the weblogic.properties
file on Unix by way of permissions/privileges that is not required on WinNT, but
was not able to find anything in the documentation.
Could anyone help, please?
Thanks.
Hrishi -
Help on File Upload on ATG Dynamo 5.6 (Servlet 2.2)
Hi,
I am using Apache Common FileUpload to upload a file on the server. It works well on Tomcat . I tried to port the same code on ATG Dynamo 5.6.1, I could not upload the files. After going deep into the problem, I got to know that Apache FileUpload has a dependancy of Servlet 2.3 Specs compliance.
While I checked the version of Servlet on ATG, it was 2.2.
Could somebody help me with the same.
I need some file upload utility that would work on ATG Dynamo.
Or atleast a way out would do.
Thanks and regards.....
KalpakTry to obtain an older version of the commons FileUpload utility if available, which is compatible with your desired version or you can use another utility that supports Servlets 2.0 provided by Oreilly Package...
The class MultipartRequest authored by oreilly that included in the package holds the whole nasty behind the scenes, here you are the link for the docs
http://www.stanford.edu/group/coursework/stanfordoki/oreilly/com.oreilly.servlet.MultipartRequest.html
And you can find the package, examples and the sources here
http://examples.oreilly.com/jservlet2/
Best Regards,
mohammed Sleem -
Session tracking for File Upload Servlet
Hey Friends,
I am developing a File Upload servlet and I need your help in certain matters .I have taken the servlet code from java-edge.com and am modifying it to give custom behaviour.I have a main page for upload (form upload)(lets call it form 1).If the file to be uploaded already exists on the server then a page is generated by the server saying that file already exists.(form 2)Now it is here(in form 2) that I want to provide an extra button which when submitted would recall the same servlet /or maybe another one and would provide the user for overriding the existing file.
Now as per the code I would set the Override flag to be false in the second form and false in the main form .
Given the case that it is a form based uploading servlet how do I maintain the user session when going to the next form or how do i pass the variables of the first form into second form .
I am also facing another problem that is how do i manage multiple file uploads at a time .This basic system allows only one file per upload .
P.S If someone could also throw some light on how to use the com.oreilly servlet (the latest version) it would be lovely but for now I want to focus on developing the current oneHi Jocelyn,
I want to apologize firstly for the delay in my response.
I was seriously bogged down due to certain circumstances and so couldnt reply.Thanks a million for your prompt reply.I'll post the Html content here and you will find the servlet code as is at the following U.R.L
http://www.java-edge.com/Viewcode.asp?Value=serv012
Form1:
<HTML>
<HEAD>
<TITLE> Upload </TITLE>
</HEAD>
<BODY >
<h2>Upload Your File!</h2>
<form ENCTYPE="multipart/form-data" action="http://localhost:8080/servlet/Upload" method=post>
click <b> browse </b>to select the file <br>
<b> File:</b>
<input type="FILE" name="Filename" value="" MAXLENGTH=255 size=50><br>
Click here to upload!<input type=submit value=Upload>
<input type=hidden name=Directory value="G:/Workspace/Upload/">
<input type=hidden name=SuccessPage value="G:/Workspace/successpage.html">
<input type=hidden name="OverWrite" value="false">
<input type=hidden name="OverWritePage" value="">
</form>
</BODY>
</HTML>
Form 2
<HTML>
<HEAD>
<TITLE> Upload </TITLE>
</HEAD>
<BODY >
<h2>Upload Your File!</h2>
<form ENCTYPE="multipart/form-data" action="http://localhost:8080/servlet/Upload" method=post>
click <b> browse </b>to select the file <br>
<b> File:</b>
<input type="FILE" name="Filename" value="" MAXLENGTH=255 size=50><br>
Click here to upload!<input type=submit value=Upload>
<input type=hidden name=Directory value="G:/Workspace/Upload/">
<input type=hidden name=SuccessPage value="G:/Workspace/successpage.html">
<input type=hidden name="OverWrite" value="true">
<input type=hidden name="OverWritePage" value="G:/Workspace/overwritepage.html">
</form>
</BODY>
</HTML>
Now in Form 2 I would add another button which when clicked would prompt the user if he wishes to overwrite the page.
I am also posting the servlet code although I am sure u would prefer reading the one on the site
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Upload extends HttpServlet
static final int Max = 102400;// max. size of the file can be 100K
String path;// stores path
String msg;// store message of success
//init method is called when servlet is first loaded
public void init(ServletConfig config)throws ServletException
super.init(config);
if(path == null)
path = "G:/Workspace/Upload/";
if(msg == null)
msg = "File successfully uploaded. Check out!";
public void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException
ServletOutputStream sos = null;
DataInputStream dis = null;
FileOutputStream fos = null;
try
resp.setContentType("text/plain");// return type of response is being set as plain
sos = resp.getOutputStream();// gets handle to the output stream
catch(IOException e)
System.out.println(e);
return;
try
String contentType = req.getContentType();// gets client's content type that should be multipart/form-data
if(contentType!=null && contentType.indexOf("multipart/form-data")!= -1)
// gets handle to the input stream to get the file to be uploaded from client
dis = new DataInputStream(req.getInputStream());
// gets length of the content data
int Length = req.getContentLength();
if(Length>Max)// length of the content data is compared with max size set
sos.println("sorry! file too large");
sos.flush();
return;
//to store the contents of file in byte array
byte arr[] = new byte[Length];
int dataRead = 0;
int totalData = 0;
while(totalData <Length)
dataRead = dis.read(arr,totalData,Length);
totalData += dataRead;
String data = new String(arr);//byte array converted to String
arr = null;
// gets boundary value
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex+1,contentType.length());
String dir = "";
if(data.indexOf("name=Directory")>0)// the type ""Directory"" is searched in the web page
dir = data.substring(data.indexOf("name=Directory"));
//gets directory
// the directory higher in the directory tree cannot be selected
if(dir.indexOf("..")>0)
sos.println("Error- the directory higher in the directory tree cannot be selected");
return;
String successPage="";
if(data.indexOf("name=\"SuccessPage\"")>0)// the type ""SuccessPage"" is searched in the web page
successPage =data.substring(data.indexOf("name=\"SuccessPage\""));
// gets successpage
String overWrite="";
if(data.indexOf("name=\"OverWrite\"")>0)// the type ""Overwrite"" is searched in the web page
overWrite =data.substring(data.indexOf("name=\"OverWrite\""));
overWrite = overWrite.substring(overWrite.indexOf("\n")+1);
overWrite = overWrite.substring(overWrite.indexOf("\n")+1);
overWrite = overWrite.substring(0,overWrite.indexOf("\n")-1);//gets overwrite flag
else
//overWrite = "false";
String overWritePage ="";
if(data.indexOf("name=\"OverWritePage\"")>0)// the type ""OverwritePage"" is searched in the web page
// ensures same file is not uploaded twice
overWritePage =data.substring(data.indexOf("name=\"OverWritePage\""));
overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);
overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);
overWritePage = overWritePage.substring(0,overWritePage.indexOf("\n")-1);// // gets overwritepage
//gets upload file name
String file =data.substring(data.indexOf("filename=\"")+10);
file = file.substring(0,file.indexOf("\n"));
file = file.substring(file.lastIndexOf("\\")+1,file.indexOf("\""));
int position;//upload file's position
position =data.indexOf("filename=\"");//find position of upload file section of request
position =data.indexOf("\n",position)+1;//find position of content-disposition line
position =data.indexOf("\n",position)+1;//find position of content-type line
position =data.indexOf("\n",position)+1;//find position of blank line
int location =data.indexOf(boundary,position)-4;//find position of next boundary marker
data =data.substring(position,location);// uploaded file lies between position and location
String fileName = new String(path + dir + file);// the complete path of uploadad file
File check = new File(fileName);
/*************************CASE OVERRIDE ************************************/
//String overwrite=req.getParameter("OverWrite");
if(check.exists())// checks for existence of file
if(overWrite.equals("false"))
if(overWritePage.equals(""))
sos.println("Sorry ,file already exists");
//return;
else
//overWritePage="G:/Workspace/overwritepage.html";
fos = new FileOutputStream(fileName);
fos.write(data.getBytes(),0,data.length());
//resp.sendRedirect(overWritePage);
sos.println("File Overridden");
//return;
File checkDir = new File(path + dir);
if(!checkDir.exists())//checks for existence of directory
checkDir.mkdirs();
fos = new FileOutputStream(fileName);
fos.write(data.getBytes(),0,data.length());
sos.println("File successfully uploaded");
if(check.exists())
if(overWrite.equals("true"))
fos = new FileOutputStream(fileName);
fos.write(data.getBytes(),0,data.length());
if(successPage.equals(""))
sos.println(msg);
sos.println("File successfully uploaded");// if success HTML page URL not received
else
successPage="G:/Workspace/successpage.html";
resp.sendRedirect(successPage);
else// incase request is not multipart
sos.println("Not multipart");
}//END OF TRY BLOCK
catch(Exception e)
try
System.out.println(e);
sos.println("unexpected error");
catch(Exception f)
System.out.println(f);
finally
try
fos.close();// file output stream closed
catch(Exception f)
System.out.println(f);
try
dis.close();// input stream to client closed
catch(Exception f)
System.out.println(f);
try
sos.close();// output stream to client closed
catch(Exception f)
System.out.println(f);
}//END OF DOPOST METHOD
} //END OF CLASS
Jocelyn the above code may have tid bit errors which u could understand.But I hope u get the overall idea of whats going on -
File Upload.. Strange Problem..
im trying to read file data and print it in the browser. I dont want to save the file. just to read the uploaded file which is TAB delimited..
First time it works fine. but If I browse back button and reload another file and submit. I am getting content of first file and second file. I closed the browser and reopened it but still problem is not resolved. it keeps on adding file content instead of showing current uploaded file. I dont know what to do.
here is my code
upload.html
<html>
<head>
<title>File Upload Form</title>
</head>
<body>
Upload File using this..
<FORM METHOD="POST" ENCTYPE="multipart/form-data" action="uploadFile.jsp">
File: <input type="file" name="file"><br>
<input value="Submit" type="submit">
</form>
</body>
</html>
UploadFile.jsp
=============
<%@page language="java" import="java.io.*" %>
<%@page language="java" import="java.util.*" %>
<%!
private BufferedInputStream bis = null;
int MAX_LINES = 2000;
private String currentLine = "";
//private String[] PartNumber;
//private String[] Quantity;
public int disp_counter = 0;
public int mime_counter = 0;
public int boundary_counter = 0;
private String content_diposition = null;
private HttpServletRequest request;
private javax.servlet.jsp.JspWriter mOut;
The incoming request needs to be an InputStream before it can be parsed. This method creates an InputStream from the request. The
request contains the uploaded file contents
public void setInputStream(HttpServletRequest request, JspWriter _out)throws IOException {
try{
bis = new BufferedInputStream(request.getInputStream());
} catch(IOException e){
e.printStackTrace();
this.request = request;
this.mOut = _out;
//mOut.println("After setting input Stream<br>");
private int getRealContentLength() throws Exception
boundary_counter = readBoundaryLength(bis);
content_diposition = readContentDisposition(bis);
//mOut.println(" getRealContentLength() content_diposition ="+content_diposition+"<br>");
mime_counter = readUntilBody(bis);
int tmpContentLength = getContentLength();
int retLength;
mOut.println(" getRealContentLength() boundary_counter ="+boundary_counter+"<br>");
mOut.println(" getRealContentLength() content_diposition ="+content_diposition+"<br>");
mOut.println(" getRealContentLength() disp_counter ="+disp_counter+"<br>");
mOut.println(" getRealContentLength() mime_counter ="+mime_counter+"<br>");
mOut.println(" getRealContentLength() tmpContentLength ="+tmpContentLength+"<br>");
retLength = getContentLength()-boundary_counter-2-mime_counter-disp_counter;
return retLength;
private int readBoundaryLength(BufferedInputStream fis) throws Exception{
//mOut.println("---- Inside readBoundaryLength ----<br>");
StringBuffer sb = new StringBuffer();
byte[] b = new byte[1];
int counter=0;
while(true){
try{
fis.read(b);
counter++;
//mOut.println("RB "+counter+"="+b[0]+"<br>");
sb.append( new String(b));
//if('\r'==b[0])
if(13==b[0]){
fis.read(b);
sb.append( new String(b));
//mOut.println("RB next="+b[0]+"<br>");
break;
}catch(IOException e){
e.printStackTrace();
//mOut.println("----Counter before return="+counter+" STR="+sb.toString()+"----<br>");
b = null;
//mOut.println("---- End readBoundaryLength ----<br>");
return counter+1;
private int readUntilBody(BufferedInputStream fis) throws Exception{
byte[] b = new byte[1];
mime_counter=0;
int counter = 0;
StringBuffer sb = new StringBuffer();
while(true){
try{
fis.read(b);
sb.append(new String(b));
mime_counter++;
//mOut.println("RUntilB "+mime_counter+"="+b[0]+"<br>");
//if('\r'==b[0])
if(13==b[0])
counter++;
if(counter == 2){
fis.read(b);
sb.append(new String(b));
//mOut.println("RUntilB counter=2 "+mime_counter+"="+b[0]+"<br>");
break;
}catch(IOException e){
e.printStackTrace();
b = null;
//mOut.println("RUntilB="+sb.toString()+"<br>");
return mime_counter;
private int getContentLength(){
return request.getContentLength();
private String readContentDisposition(BufferedInputStream fis) throws Exception{
byte[] b = new byte[1];
disp_counter=0;
StringBuffer sb = new StringBuffer();
while(true){
try{
fis.read(b);
disp_counter++;
sb.append(new String(b));
//mOut.println("ReadCD "+disp_counter+"="+b[0]+"<br>");
//if('\r'==b[0])
if(13==b[0]){
for(int i=1; i < 2; i++){
sb.append(new String(b));
fis.read(b);
//mOut.println("ReadCD before break="+b[0]+"<br>");
break;
}catch(IOException e){
e.printStackTrace();
//mOut.println("----disp_counter before return="+disp_counter+" STR="+sb.toString()+"----<br>");
b=null;
disp_counter += 1;
return sb.toString();
private String readNumberOfBytes(BufferedInputStream bis, int count) throws Exception{
byte[] b = new byte[count];
byte[] tmp = new byte[count];
int offset = 0;
int icount = count;
int i=0;
String tmpStr = null;
try{
while((i = bis.read(b,0,icount)) != -1){
System.arraycopy(b,0,tmp,offset,i);
tmpStr = new String( tmp );
//mOut.println( "*****"+tmpStr );
if(icount - i > 0) {
icount = count - i;
offset +=i;
continue;
else
break;
}catch(IOException e){
e.printStackTrace();
//for (i=0; i<b.length; i++)
// mOut.println("AC"+i+"="+b+"<br>");
return tmpStr;
public String parseFile( ) throws Exception {
int len = readAll(bis);
mOut.println("total len="+len+"<br>");
//in the first phase, throw away the request parameters that are not required
//in the second phase, grab the required stuff
int reallength;
int mod = 0;
int div = 0;
//get rid of the unwanted request content
reallength = getRealContentLength();//this is the orig line
//mOut.println( "reallength is " + reallength +"<br>");
//get rid of boundary and content disp header.
//int bound_len = readBoundaryLength(bis);
//String content_disp = readContentDisposition(bis);
//mOut.println( "Xbound_len" + bound_len +"<br>");
//mOut.println( "xcontent_disp" + content_disp +"<br>");
//now we are at partnos,qty
//int body = readUntilBody(bis);
if(reallength < 2048){
currentLine += readNumberOfBytes(bis,reallength);
else{
div = reallength / 2048;//buffer default size
mod = reallength % 2048;
mOut.println("div ="+div+" mod="+mod+"<br>");
for(int i=0; i < div; i++)
currentLine += readNumberOfBytes(bis,2048);
if(mod != 0)
currentLine += readNumberOfBytes(bis,mod);
//mOut.println( "currentLine" + currentLine );
//ExtractPartNumberAndQuantity();
//mOut.println("total length="+currentLine.length()+"<br>");
int lastInd = currentLine.lastIndexOf('\r');
//mOut.println("lastInd="+lastInd+"<br>");
lastInd = currentLine.lastIndexOf('\r',lastInd-1);
//mOut.println("lastInd="+lastInd+"<br>");
currentLine= currentLine.substring(0,lastInd);
//mOut.println( "currentLine="+currentLine+"<br>" );
return currentLine;
%>
<%
out.println(" request length="+request.getContentLength()+"<br>");
setInputStream(request,out);
String allLines = parseFile();
out.println("************** Parsing string starts <br>");
StringBuffer sb = new StringBuffer();
sb.append( (char)13 );
sb.append( (char)10 );
StringTokenizer st = new StringTokenizer( allLines,sb.toString());
String line = null;
// skip the first line as this is header...
if( st.hasMoreTokens() )
line = st.nextToken();
while( st.hasMoreTokens() )
line = st.nextToken();
out.println(line+"<br>");
out.flush();
%>err..
<%!
private BufferedInputStream bis = null;
int MAX_LINES = 2000;
private String currentLine = "";
//private String[] PartNumber;
//private String[] Quantity;
public int disp_counter = 0;
public int mime_counter = 0;
public int boundary_counter = 0;
private String content_diposition = null;
private HttpServletRequest request;
private javax.servlet.jsp.JspWriter mOut;
that's the problem, most likely.... the <%! part to hold all the variables. Particularly coudl've been a problem if you have multple requests at the same time..
Maybe you are looking for
-
Is there any way to do a live video shoot using two cameras with FCX? If so how?
-
Owner of schema SYS_REPL and table RS_REPLICATION_COMPONENTS
Hello Tobias, in your SLT guides is stated that the schema SYS_REPL gets created during the first use of SLT. You recommend to use the user SYSTEM or another user with similar privileges for the initial creation. Since i'm about to implement a proper
-
I have a PAL 25fps clip that I want to export with timecode in vision. When I add the timecode effect in prem CS4, the timecode is shown as 30fps drop frame. The sequence is set up as 25fps, so can I change the effect's settings? It all worked very w
-
How to sharpen handwriting on photos of archival pages?
I got a lot of photographs of 17/18/19-century archives, with texts in dutch, latin, french, german handwriting. In some cases it is very difficult to decipher the text. Are there handy procedures (using Photoshop CS6 or CC) for sharpening the handwr
-
Photosmart C6380 compatible with airprint?
photosmart C6380 compatible for airprint This question was solved. View Solution.