leogc
asked on
File Upload using JSP
I want to attach a file of maximum size 2MB.How to do file attachment on click of button and how to check for the size of the file to be less than 2MB.
ASKER
Thanks for the reply.I went through the contents of website http://jakarta.apache.org/commons/fileupload
.But i want more detailed explanation of customising File Upload through jakarta commons file upload.I tried a sample program of uploading file through whatever the code u have mentioned here.But it displays some popup
message before uploading which I dont want or rather customise the file upload functionality.
Regards
Leo
.But i want more detailed explanation of customising File Upload through jakarta commons file upload.I tried a sample program of uploading file through whatever the code u have mentioned here.But it displays some popup
message before uploading which I dont want or rather customise the file upload functionality.
Regards
Leo
What was the pop up message?
ASKER
While I am trying to upload the file from browser to the database,it is showing the dialog box of the file download i.e Would you like to open the file or save it to computer and my snippet of servlet code is as follows:
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti on
{
res.setContentType("multip art/form-d ata");
PrintWriter pw=res.getWriter();
fileUploadHandler(req);
}
void fileUploadHandler(HttpServ letRequest req){
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory) ;
// Parse the request
try{
List items = upload.parseRequest(req);
}catch(Exception e){
System.out.println("error" +e.getMess age());
e.printStackTrace();
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti
{
res.setContentType("multip
PrintWriter pw=res.getWriter();
fileUploadHandler(req);
}
void fileUploadHandler(HttpServ
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory)
// Parse the request
try{
List items = upload.parseRequest(req);
}catch(Exception e){
System.out.println("error"
e.printStackTrace();
}
}
Why are you getting the writer?
ASKER
Even if I remove the writer the same File download dialog box is appearing.
One more thing is how to get the file name of the uploaded file in the servlet handling the uploaded file.I tried the following code snippet specified in one of the links provided in this site.But it is going to infinite loop at the line pos = fileData.indexOf("filename =\"", startPos);
code snippet:
int formDataLength=request.get ContentLen gth();
byte dataBytes[]=new byte[formDataLength];
byte[] line=new byte[128];
int count=0;
String s="";
String fileData="";
int pos=0;
int startPos=0;
int endPos=0;
do
{
copyByte(dataBytes, line, count ,1); //read 1 byte at a time
count+=1;
s = new String(line, 0, 1);
fileData = fileData + s;
pos = fileData.indexOf("filename =\"", startPos); //set the file name
if(pos != -1)
startPos = pos;
}while(pos == -1);
void copyByte(byte [] fromBytes, byte [] toBytes, int start, int len)
{
for(int i=start;i<(start+len);i++)
{
toBytes[i - start] = fromBytes[start];
}
}
One more thing is how to get the file name of the uploaded file in the servlet handling the uploaded file.I tried the following code snippet specified in one of the links provided in this site.But it is going to infinite loop at the line pos = fileData.indexOf("filename
code snippet:
int formDataLength=request.get
byte dataBytes[]=new byte[formDataLength];
byte[] line=new byte[128];
int count=0;
String s="";
String fileData="";
int pos=0;
int startPos=0;
int endPos=0;
do
{
copyByte(dataBytes, line, count ,1); //read 1 byte at a time
count+=1;
s = new String(line, 0, 1);
fileData = fileData + s;
pos = fileData.indexOf("filename
if(pos != -1)
startPos = pos;
}while(pos == -1);
void copyByte(byte [] fromBytes, byte [] toBytes, int start, int len)
{
for(int i=start;i<(start+len);i++)
{
toBytes[i - start] = fromBytes[start];
}
}
please post your entire code and I'l have a look on monday
ASKER
My JSP page is common to both the questions i.e (1)dialog box is appearing when I
Try to upload the file (2)how to get the filename of the uploaded file in file upload handler servlet.
jsp code
<html>
<head>
<script>
function uploadfile()
{
form=document.forms[0];
form.action="/samples/file upload";
form.submit();
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-da ta">
<font color="blue" size="5">Attach Files</font><br>
Click "Browse" to select a file.You can attach files up to a<br>
total message size of 2.0MB.<br>
File :<input type="file" name="file1"/><br>
<br><br>
<input type="button" value="Attach Files" onclick="uploadfile()"/>
</form>
</body>
</html>
1.Servlet code for first question.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl oad.disk.D iskFileIte mFactory;
import org.apache.commons.fileupl oad.FileIt emFactory;
import org.apache.commons.fileupl oad.servle t.ServletF ileUpload;
public class FileUpload extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti on
{
res.setContentType("multip art/form-d ata");
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory) ;
try{
List items = upload.parseRequest(req);
}catch(Exception e){
System.out.println("error" +e.getMess age());
e.printStackTrace();
}
}
}
2.Servlet code for second question i.e. how to get the file name of uploaded file.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class FileUpload extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti on
{
res.setContentType("multip art/form-d ata");
int formDataLength=req.getCont entLength( );
byte dataBytes[]=new byte[formDataLength];
byte[] line=new byte[128];
int count=0;
String s="";
String fileData="";
int pos=0;
int startPos=0;
int endPos=0;
String boundary="";
String filename="";
String strLocalFileName="";
do
{
copyByte(dataBytes, line, count ,1); //read 1 byte at a time
count+=1;
s = new String(line, 0, 1);
fileData = fileData + s;
pos = fileData.indexOf("Content- Dispositio n: form-data; name=\"");
if(pos != -1)
endPos = pos;
}while(pos == -1);
boundary = fileData.substring(startPo s, endPos);
System.out.println("BOUNDA RY"+bounda ry);
do
{
copyByte(dataBytes, line, count ,1); //read 1 byte at a time
count+=1;
s = new String(line, 0, 1);
fileData = fileData + s;
pos = fileData.indexOf("Content- Type: ", startPos);
if(pos != -1)
endPos = pos;
}while(pos == -1);
filename = fileData.substring(startPo s + 10, endPos - 3);
strLocalFileName = filename;
int index = filename.lastIndexOf("\\") ;
if(index != -1)
filename = filename.substring(index + 1);
else
filename = filename;
System.out.println("FILENA ME"+filena me);
}
void copyByte(byte [] fromBytes, byte [] toBytes, int start, int len)
{
for(int i=start;i<(start+len);i++)
{
toBytes[i - start] = fromBytes[start];
}
}
}
Try to upload the file (2)how to get the filename of the uploaded file in file upload handler servlet.
jsp code
<html>
<head>
<script>
function uploadfile()
{
form=document.forms[0];
form.action="/samples/file
form.submit();
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-da
<font color="blue" size="5">Attach Files</font><br>
Click "Browse" to select a file.You can attach files up to a<br>
total message size of 2.0MB.<br>
File :<input type="file" name="file1"/><br>
<br><br>
<input type="button" value="Attach Files" onclick="uploadfile()"/>
</form>
</body>
</html>
1.Servlet code for first question.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl
import org.apache.commons.fileupl
import org.apache.commons.fileupl
public class FileUpload extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti
{
res.setContentType("multip
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory)
try{
List items = upload.parseRequest(req);
}catch(Exception e){
System.out.println("error"
e.printStackTrace();
}
}
}
2.Servlet code for second question i.e. how to get the file name of uploaded file.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class FileUpload extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti
{
res.setContentType("multip
int formDataLength=req.getCont
byte dataBytes[]=new byte[formDataLength];
byte[] line=new byte[128];
int count=0;
String s="";
String fileData="";
int pos=0;
int startPos=0;
int endPos=0;
String boundary="";
String filename="";
String strLocalFileName="";
do
{
copyByte(dataBytes, line, count ,1); //read 1 byte at a time
count+=1;
s = new String(line, 0, 1);
fileData = fileData + s;
pos = fileData.indexOf("Content-
if(pos != -1)
endPos = pos;
}while(pos == -1);
boundary = fileData.substring(startPo
System.out.println("BOUNDA
do
{
copyByte(dataBytes, line, count ,1); //read 1 byte at a time
count+=1;
s = new String(line, 0, 1);
fileData = fileData + s;
pos = fileData.indexOf("Content-
if(pos != -1)
endPos = pos;
}while(pos == -1);
filename = fileData.substring(startPo
strLocalFileName = filename;
int index = filename.lastIndexOf("\\")
if(index != -1)
filename = filename.substring(index + 1);
else
filename = filename;
System.out.println("FILENA
}
void copyByte(byte [] fromBytes, byte [] toBytes, int start, int len)
{
for(int i=start;i<(start+len);i++)
{
toBytes[i - start] = fromBytes[start];
}
}
}
ASKER
I didnt get any solution to the question what ever i had posted.What should i do to the question
While we wait for bloodredsun to get back here, maybe I can help you.
>1)dialog box is appearing when I Try to upload the file
That is surprising. I can't understand that.
>(2)how to get the filename of the uploaded file
You can use the apache code for that. Use something like the following.
String filename = "file name from client";
for (int i = 0; i < items.size(); i ++) {
FileItem item = (FileItem) items.get(i);
if(item.isFormField()){
}
else fileName = item.getName();
}
>1)dialog box is appearing when I Try to upload the file
That is surprising. I can't understand that.
>(2)how to get the filename of the uploaded file
You can use the apache code for that. Use something like the following.
String filename = "file name from client";
for (int i = 0; i < items.size(); i ++) {
FileItem item = (FileItem) items.get(i);
if(item.isFormField()){
}
else fileName = item.getName();
}
ASKER
can u throw some more light on whatever code u have sent in detail.I am not able to understand what is this u r talking about file name from client.My jsp contains a text field also. I want to retrieve that data also in my servlet.I forgot to mention that in my jsp.
The getName method will give the name of the file that it had on the client's machine before it was uploaded. Just put it into your code something like this to test.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl oad.disk.D iskFileIte mFactory;
import org.apache.commons.fileupl oad.FileIt emFactory;
import org.apache.commons.fileupl oad.servle t.ServletF ileUpload;
public class FileUpload extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOExcepti on
{
res.setContentType("multip art/form-d ata");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory) ;
try{
List items = upload.parseRequest(req);
for (int i = 0; i < items.size(); i ++) {
FileItem item = (FileItem) items.get(i);
if(!item.isFormField()) System.out.println("file name is " + item.getName());
}
}catch(Exception e){
System.out.println("error" +e.getMess age());
e.printStackTrace();
}
}
}
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl
import org.apache.commons.fileupl
import org.apache.commons.fileupl
public class FileUpload extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOExcepti
{
res.setContentType("multip
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory)
try{
List items = upload.parseRequest(req);
for (int i = 0; i < items.size(); i ++) {
FileItem item = (FileItem) items.get(i);
if(!item.isFormField()) System.out.println("file name is " + item.getName());
}
}catch(Exception e){
System.out.println("error"
e.printStackTrace();
}
}
}
ASKER
I am still getting the File Download dialog box after using
what ever code u have sent above.This is causing a lot of problem to me.Can anyone pls tell me why i am getting this dialog box.Does it depend on the OS.I am using Windows XP as OS.
what ever code u have sent above.This is causing a lot of problem to me.Can anyone pls tell me why i am getting this dialog box.Does it depend on the OS.I am using Windows XP as OS.
>I am still getting the File Download dialog box after using what ever code u have sent above.
I can't explain it. Hopefully bloodredsun will find time to help you.
I can't explain it. Hopefully bloodredsun will find time to help you.
ASKER
hi
bloodredsun any comments from u on why I am getting the file download dialog box will be greatly helpful to me.Do u people are also facing this problem?
bloodredsun any comments from u on why I am getting the file download dialog box will be greatly helpful to me.Do u people are also facing this problem?
ASKER
I did not get any solution to this question regarding why the download dialog box is comming.What should be done to this question.
What version of FileUpload are you using ? Please post the minimum code that will show the behavior you describe. I will try to reproduce it on my machine. rrz
ASKER
I am using commons-fileupload-1.1.jar and commons-io-1.1.jar.My jsp page and servlet code are as follows:
jsp page:
<html>
<head>
<script>
function uploadfile()
{
form=document.forms[0];
form.action="/samples/file upload";
form.submit();
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-da ta">
<font color="blue" size="5">Attach Files</font><br>
Click "Browse" to select a file.You can attach files up to a<br>
total message size of 10.0MB.<br>
File 1:<input type="file" name="file1"/><br>
<input type="button" value="Attach Files" onclick="uploadfile()"/>
</form>
</body>
</html>
servlet code:
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl oad.disk.D iskFileIte mFactory;
import org.apache.commons.fileupl oad.FileIt emFactory;
import org.apache.commons.fileupl oad.servle t.ServletF ileUpload;
public class FileUpload extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti on
{
res.setContentType("multip art/form-d ata");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory) ;
try{
List items = upload.parseRequest(req);
}catch(Exception e){
System.out.println("error" +e.getMess age());
e.printStackTrace();
}
}
}
jsp page:
<html>
<head>
<script>
function uploadfile()
{
form=document.forms[0];
form.action="/samples/file
form.submit();
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-da
<font color="blue" size="5">Attach Files</font><br>
Click "Browse" to select a file.You can attach files up to a<br>
total message size of 10.0MB.<br>
File 1:<input type="file" name="file1"/><br>
<input type="button" value="Attach Files" onclick="uploadfile()"/>
</form>
</body>
</html>
servlet code:
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl
import org.apache.commons.fileupl
import org.apache.commons.fileupl
public class FileUpload extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti
{
res.setContentType("multip
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory)
try{
List items = upload.parseRequest(req);
}catch(Exception e){
System.out.println("error"
e.printStackTrace();
}
}
}
Ok, I see the behavior that you describe. I can't explain it. Hopefully bloodredsun can explain. Please don't close this question until we get an explaination.
I did come up with the following working code. rrz
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl oad.disk.D iskFileIte mFactory;
import org.apache.commons.fileupl oad.*;
import org.apache.commons.fileupl oad.servle t.*;
public class leogc extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti on
{
res.setContentType("text/h tml");
PrintWriter out = res.getWriter();
RequestContext reqContext = new ServletRequestContext(req) ;
if(FileUploadBase.isMultip artContent (reqContex t)){
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory) ;
try{
List items = upload.parseRequest(reqCon text);
out.println("<html>");
out.println("<head><title> File Upload</title></head>");
out.println("<body>");
out.println("Received file.");
out.println("</body></html >");
}catch(Exception e){
System.out.println("error" +e.getMess age());
e.printStackTrace();
}
} else{
out.println("<html>");
out.println("<head><title> File Upload</title></head>");
out.println("<body>");
out.println("Problem at server.");
out.println("</body></html >");
}
}
}
I did come up with the following working code. rrz
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl
import org.apache.commons.fileupl
import org.apache.commons.fileupl
public class leogc extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti
{
res.setContentType("text/h
PrintWriter out = res.getWriter();
RequestContext reqContext = new ServletRequestContext(req)
if(FileUploadBase.isMultip
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory)
try{
List items = upload.parseRequest(reqCon
out.println("<html>");
out.println("<head><title>
out.println("<body>");
out.println("Received file.");
out.println("</body></html
}catch(Exception e){
System.out.println("error"
e.printStackTrace();
}
} else{
out.println("<html>");
out.println("<head><title>
out.println("<body>");
out.println("Problem at server.");
out.println("</body></html
}
}
}
>I did not get any solution to this question regarding why the download dialog box is comming
This lastest version of fileupload seems to be dependent on commons io ( where as version 1.0 was not).
At first I thought that your omission of
> res.setContentType("text/h tml");
was the problem,but that didn't seem to solve it.
Give points to whoever can explain. rrz
This lastest version of fileupload seems to be dependent on commons io ( where as version 1.0 was not).
At first I thought that your omission of
> res.setContentType("text/h
was the problem,but that didn't seem to solve it.
Give points to whoever can explain. rrz
I guess no one will help. Did you try my last code ?
ASKER
No I have not tried yet.Give me some time.Assuming this code works what i am planning to do is get the file name,rename the file,build a path on the server and store the renamed file in the directory created under the built path.Store the build path in the database.will it be possible to do the above with whatever the code u have sent.
>will it be possible to do the above with whatever the code u have sent.
The code above just uploads the file. First get that working. I can help you with the rest as well. But first look at the examples on the Jacarkta site. It shows how to get hold of the FileItem you want to use.
The code above just uploads the file. First get that working. I can help you with the rest as well. But first look at the examples on the Jacarkta site. It shows how to get hold of the FileItem you want to use.
ASKER
Thanks for the reply.The code which u sent has solved the problem of pop up window which was appearing.
Now i am trying to store the uploaded file in some directory on the server.Any inputs on how to upload
and store the file on the server will be helpful.
Now i am trying to store the uploaded file in some directory on the server.Any inputs on how to upload
and store the file on the server will be helpful.
>Now i am trying to store the uploaded file in some directory on the server
Please show your code. Did you add code to my posted code in order to get hold of the uploaded file ? Do you want to place file within your web app ? Are you using something like the following ?
FileWriter fw = new FileWriter(new File(application.getRealPa th("/"),"u ploadedFil e.txt"));
where application is your web app's context.
Please show your code. Did you add code to my posted code in order to get hold of the uploaded file ? Do you want to place file within your web app ? Are you using something like the following ?
FileWriter fw = new FileWriter(new File(application.getRealPa
where application is your web app's context.
ASKER
I have written the following servlet to upload the file and store it in some directory on server.Is there any way to optimize this code because I am using File class to get the filename and build the path and FileInputStream for reading the contents of the file.
Is this the way they do the file upload in realtime i.e build the output file path,read the
Input file contents and write to some location on the built server path.
One more thing I want to do now is restrict the size of the uploaded file.How to do this.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl oad.disk.D iskFileIte mFactory;
import org.apache.commons.fileupl oad.*;
import org.apache.commons.fileupl oad.servle t.*;
public class UploadServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti on
{
res.setContentType("text/h tml");
PrintWriter out = res.getWriter();
String inputFileName;
String outputFileName=null;
String path;
String filePart1;
String filePart2;
RequestContext reqContext = new ServletRequestContext(req) ;
Properties props=System.getProperties ();
String fileSeparator=props.getPro perty("fil e.separato r");
String serverPath=getServletConte xt().getRe alPath(fil eSeparator );
String finalPath=serverPath+"temp ";
System.out.println("path is "+finalPath);
File outFile=new File(finalPath);
outFile.mkdir();
File fc=outFile.getCanonicalFil e();
System.out.println("FILE NAME"+fc.getName());
if(FileUploadBase.isMultip artContent (reqContex t)){
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory) ;
try{
List items = upload.parseRequest(reqCon text);
FileItem item = (FileItem) items.get(0);
path=item.getName();
File inFile=new File(path);
inputFileName=inFile.getNa me();
System.out.println("input file name is " + inputFileName);
filePart1=inputFileName.su bstring(0, inputFileN ame.lastIn dexOf(".") );
filePart2=inputFileName.su bstring(in putFileNam e.lastInde xOf("."));
if(fc.isDirectory()){
int j=fc.list().length;
outputFileName=filePart1+I nteger.toS tring(j)+f ilePart2;
}
/*out.println("<html>");
out.println("<head><title> File Upload</title></head>");
out.println("<body>");
out.println("Received file.");
out.println("</body></html >");*/
System.out.println("file uploaded successfully "+outputFileName);
FileInputStream inputStream=new FileInputStream(path);
FileOutputStream fout=new FileOutputStream(finalPath +"\\"+outp utFileName );
int i=0;
while((i=inputStream.read( ))!=-1){
fout.write(i);
}
fout.close();
inputStream.close();
System.out.println("filein "+fc.list( ).length);
}catch(Exception e){
System.out.println("error" +e.getMess age());
e.printStackTrace();
}
} else{
/*out.println("<html>");
out.println("<head><title> File Upload</title></head>");
out.println("<body>");
out.println("Problem at server.");
out.println("</body></html >");*/
}
}
}
Is this the way they do the file upload in realtime i.e build the output file path,read the
Input file contents and write to some location on the built server path.
One more thing I want to do now is restrict the size of the uploaded file.How to do this.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl
import org.apache.commons.fileupl
import org.apache.commons.fileupl
public class UploadServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti
{
res.setContentType("text/h
PrintWriter out = res.getWriter();
String inputFileName;
String outputFileName=null;
String path;
String filePart1;
String filePart2;
RequestContext reqContext = new ServletRequestContext(req)
Properties props=System.getProperties
String fileSeparator=props.getPro
String serverPath=getServletConte
String finalPath=serverPath+"temp
System.out.println("path is "+finalPath);
File outFile=new File(finalPath);
outFile.mkdir();
File fc=outFile.getCanonicalFil
System.out.println("FILE NAME"+fc.getName());
if(FileUploadBase.isMultip
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory)
try{
List items = upload.parseRequest(reqCon
FileItem item = (FileItem) items.get(0);
path=item.getName();
File inFile=new File(path);
inputFileName=inFile.getNa
System.out.println("input file name is " + inputFileName);
filePart1=inputFileName.su
filePart2=inputFileName.su
if(fc.isDirectory()){
int j=fc.list().length;
outputFileName=filePart1+I
}
/*out.println("<html>");
out.println("<head><title>
out.println("<body>");
out.println("Received file.");
out.println("</body></html
System.out.println("file uploaded successfully "+outputFileName);
FileInputStream inputStream=new FileInputStream(path);
FileOutputStream fout=new FileOutputStream(finalPath
int i=0;
while((i=inputStream.read(
fout.write(i);
}
fout.close();
inputStream.close();
System.out.println("filein
}catch(Exception e){
System.out.println("error"
e.printStackTrace();
}
} else{
/*out.println("<html>");
out.println("<head><title>
out.println("<body>");
out.println("Problem at server.");
out.println("</body></html
}
}
}
>One more thing I want to do now is restrict the size of the uploaded file.How to do this.
Did you see the setSizeThreshold method of DiskFileItemFactory ?
http://jakarta.apache.org/commons/fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html
Did you see the setSizeThreshold method of DiskFileItemFactory ?
http://jakarta.apache.org/commons/fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html
ASKER
what about other parts of question i.e.the real time file upload and code optimisation.
Sorry, I have been very busy. You could this many ways. Here is an example.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl oad.disk.D iskFileIte mFactory;
import org.apache.commons.fileupl oad.*;
import org.apache.commons.fileupl oad.servle t.*;
public class leogc extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti on
{
res.setContentType("text/h tml");
PrintWriter out = res.getWriter();
RequestContext reqContext = new ServletRequestContext(req) ;
String dirPath=getServletContext( ).getRealP ath("/temp ");
File dir = new File(dirPath); //just make temp dir manually before hand
if(FileUploadBase.isMultip artContent (reqContex t)){
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory) ;
try{
List items = upload.parseRequest(reqCon text);
FileItem item = (FileItem) items.get(0);
String clientName = item.getName();
File file = File.createTempFile("uploa d",
clientName.substring(clien tName.last IndexOf(". ")) ,
dir);
item.write(file);
out.println("<html>");
out.println("<head><title> File Upload</title></head>");
out.println("<body>");
out.println("Your file was uploaded to " + file.getName());
out.println("</body></html >");
}catch(Exception e){
System.out.println("error" +e.getMess age());
e.printStackTrace();
}
} else{
out.println("<html>");
out.println("<head><title> Uploading Error</title></head>");
out.println("<body>");
out.println("Problem at server.");
out.println("</body></html >");
}
}
}
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl
import org.apache.commons.fileupl
import org.apache.commons.fileupl
public class leogc extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti
{
res.setContentType("text/h
PrintWriter out = res.getWriter();
RequestContext reqContext = new ServletRequestContext(req)
String dirPath=getServletContext(
File dir = new File(dirPath); //just make temp dir manually before hand
if(FileUploadBase.isMultip
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory)
try{
List items = upload.parseRequest(reqCon
FileItem item = (FileItem) items.get(0);
String clientName = item.getName();
File file = File.createTempFile("uploa
clientName.substring(clien
dir);
item.write(file);
out.println("<html>");
out.println("<head><title>
out.println("<body>");
out.println("Your file was uploaded to " + file.getName());
out.println("</body></html
}catch(Exception e){
System.out.println("error"
e.printStackTrace();
}
} else{
out.println("<html>");
out.println("<head><title>
out.println("<body>");
out.println("Problem at server.");
out.println("</body></html
}
}
}
ASKER
I tried using this program.If i use this program i dodnt have control over the filename after uploading.I want to rename the file as uploadedfilename1,uploaded filename2. how to do this.
one more thing i dodnt want to upload files which are more than 2 mb files.so i tried the following code:
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(2 000);
but still it is uploading the file more than 2mb. once the file size exceeds 2mb size
i want to display a message "file size with more than 2mb cannot be uploaded".How to do this.
regards
leo
one more thing i dodnt want to upload files which are more than 2 mb files.so i tried the following code:
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(2
but still it is uploading the file more than 2mb. once the file size exceeds 2mb size
i want to display a message "file size with more than 2mb cannot be uploaded".How to do this.
regards
leo
>I want to rename the file as uploadedfilename1,uploaded filename2.
If we assume that dirPath points to the directory that you are putting the files then
File dir = new File(dirPath);
int number = dir.list().length; // assuming that dir only contains the uploaded files.
// then down in try block you could use
File file = new File("uploadedfilename" + number +
clientName.substring(clien tName.last IndexOf(". ") -1) ,
dir);
>i want to display a message "file size with more than 2mb cannot be uploaded".
you could use
if(item.getSize() > 2000000){ }
but it might be easier to change
if(FileUploadBase.isMultip artContent (reqContex t)){
to
if(FileUploadBase.isMultip artContent (reqContex t) && reqContext.getContentLengt h() < 2000000){
see
http://jakarta.apache.org/commons/fileupload/apidocs/org/apache/commons/fileupload/RequestContext.html
I didn't have time to test. Post your code if you have a problem. rrz
If we assume that dirPath points to the directory that you are putting the files then
File dir = new File(dirPath);
int number = dir.list().length; // assuming that dir only contains the uploaded files.
// then down in try block you could use
File file = new File("uploadedfilename" + number +
clientName.substring(clien
dir);
>i want to display a message "file size with more than 2mb cannot be uploaded".
you could use
if(item.getSize() > 2000000){ }
but it might be easier to change
if(FileUploadBase.isMultip
to
if(FileUploadBase.isMultip
see
http://jakarta.apache.org/commons/fileupload/apidocs/org/apache/commons/fileupload/RequestContext.html
I didn't have time to test. Post your code if you have a problem. rrz
ASKER
File file = new File("uploadedfilename" + number +
clientName.substring(clien tName.last IndexOf(". ") -1) ,
dir);
the above code is causing compilation problem.
cannot resolve symbol
[javac] symbol : constructor File (java.lang.String,java.io. File)
[javac] location: class java.io.File
[javac] File file = new File("uploadedfilename" + number + +clientName.substring(clie ntName.las tIndexOf(" .") -1),dir);
clientName.substring(clien
dir);
the above code is causing compilation problem.
cannot resolve symbol
[javac] symbol : constructor File (java.lang.String,java.io.
[javac] location: class java.io.File
[javac] File file = new File("uploadedfilename" + number + +clientName.substring(clie
My mistake, I put the parameters in the wrong order. See
http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html
and try
File file = new File( dir,
"uploadedfilename" + number +
clientName.substring(clien tName.last IndexOf(". ") -1) );
I hope your learning something. rrz
http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html
and try
File file = new File( dir,
"uploadedfilename" + number +
clientName.substring(clien
I hope your learning something. rrz
ASKER
The above code is not renaming the file in the expected format.For example if i have a file named link.txt,i want to rename the file as link1.txt but the above code is renaming as uploadedfilename1k.txt .
Also reqContext.getContentLengt h() gives the length of the request.It does not give the size of the uploaded file.If my request contains addtional textfield
values then reqContext.getContentLengt h() gives the length of request but not the
exact size of uploaded file.In this case how to check for the uploaded file size.Any suggestions on this will be helpful.
Regards
leo
Also reqContext.getContentLengt
values then reqContext.getContentLengt
exact size of uploaded file.In this case how to check for the uploaded file size.Any suggestions on this will be helpful.
Regards
leo
I had some to test this one. I hope your happy. rrz
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl oad.disk.D iskFileIte mFactory;
import org.apache.commons.fileupl oad.*;
import org.apache.commons.fileupl oad.servle t.*;
public class leogc2 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti on
{
res.setContentType("text/h tml");
PrintWriter out = res.getWriter();
RequestContext reqContext = new ServletRequestContext(req) ;
String dirPath = getServletContext().getRea lPath("/te mp");
File dir = new File(dirPath); //just make temp dir manually before hand
int number = dir.list().length;
if(FileUploadBase.isMultip artContent (reqContex t)){
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory) ;
try{
out.println("<html>");
out.println("<head><title> File Upload</title></head>");
out.println("<body>");
List items = upload.parseRequest(reqCon text);
FileItem item = (FileItem) items.get(0);
if(item.getSize() < 2000000){
String fileName = item.getName();
int index1 = fileName.lastIndexOf("\\") ;
if(index1 != -1)fileName = fileName.substring(index1 + 1);
else{
int index2 = fileName.lastIndexOf("/");
if(index2 != -1)fileName = fileName.substring(index1 + 1);
}
int index3 = fileName.lastIndexOf(".");
if(index3 != -1){
fileName = fileName.substring(0,index 3) + number
+ fileName.substring(index3) ;
File file = new File(dirPath,fileName);
item.write(file);
out.println("Your file was uploaded to " + file.getName());
}else{
out.println("No file was not uploaded!");
}
}else out.println("File is too big!");
out.println("</body></html >");
}catch(Exception e){
System.out.println("error" +e.getMess age());
e.printStackTrace();
}
} else{
out.println("<html>");
out.println("<head><title> Uploading Error</title></head>");
out.println("<body>");
out.println("Problem at server.");
out.println("</body></html >");
}
}
}
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl
import org.apache.commons.fileupl
import org.apache.commons.fileupl
public class leogc2 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti
{
res.setContentType("text/h
PrintWriter out = res.getWriter();
RequestContext reqContext = new ServletRequestContext(req)
String dirPath = getServletContext().getRea
File dir = new File(dirPath); //just make temp dir manually before hand
int number = dir.list().length;
if(FileUploadBase.isMultip
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory)
try{
out.println("<html>");
out.println("<head><title>
out.println("<body>");
List items = upload.parseRequest(reqCon
FileItem item = (FileItem) items.get(0);
if(item.getSize() < 2000000){
String fileName = item.getName();
int index1 = fileName.lastIndexOf("\\")
if(index1 != -1)fileName = fileName.substring(index1 + 1);
else{
int index2 = fileName.lastIndexOf("/");
if(index2 != -1)fileName = fileName.substring(index1 + 1);
}
int index3 = fileName.lastIndexOf(".");
if(index3 != -1){
fileName = fileName.substring(0,index
+ fileName.substring(index3)
File file = new File(dirPath,fileName);
item.write(file);
out.println("Your file was uploaded to " + file.getName());
}else{
out.println("No file was not uploaded!");
}
}else out.println("File is too big!");
out.println("</body></html
}catch(Exception e){
System.out.println("error"
e.printStackTrace();
}
} else{
out.println("<html>");
out.println("<head><title>
out.println("<body>");
out.println("Problem at server.");
out.println("</body></html
}
}
}
oops lost the first few lines.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl oad.disk.D iskFileIte mFactory;
import org.apache.commons.fileupl oad.*;
import org.apache.commons.fileupl oad.servle t.*;
public class leogc2 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti on
{
res.setContentType("text/h tml");
PrintWriter out = res.getWriter();
RequestContext reqContext = new ServletRequestContext(req) ;
String dirPath = getServletContext().getRea lPath("/te mp");
File dir = new File(dirPath); //just make temp dir manually before hand
int number = dir.list().length;
if(FileUploadBase.isMultip artContent (reqContex t)){
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory) ;
try{
out.println("<html>");
out.println("<head><title> File Upload</title></head>");
out.println("<body>");
List items = upload.parseRequest(reqCon text);
FileItem item = (FileItem) items.get(0);
if(item.getSize() < 2000000){
String fileName = item.getName();
int index1 = fileName.lastIndexOf("\\") ;
if(index1 != -1)fileName = fileName.substring(index1 + 1);
else{
int index2 = fileName.lastIndexOf("/");
if(index2 != -1)fileName = fileName.substring(index1 + 1);
}
int index3 = fileName.lastIndexOf(".");
if(index3 != -1){
fileName = fileName.substring(0,index 3) + number
+ fileName.substring(index3) ;
File file = new File(dirPath,fileName);
item.write(file);
out.println("Your file was uploaded to " + file.getName());
}else{
out.println("No file was not uploaded!");
}
}else out.println("File is too big!");
out.println("</body></html >");
}catch(Exception e){
System.out.println("error" +e.getMess age());
e.printStackTrace();
}
} else{
out.println("<html>");
out.println("<head><title> Uploading Error</title></head>");
out.println("<body>");
out.println("Problem at server.");
out.println("</body></html >");
}
}
}
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl
import org.apache.commons.fileupl
import org.apache.commons.fileupl
public class leogc2 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti
{
res.setContentType("text/h
PrintWriter out = res.getWriter();
RequestContext reqContext = new ServletRequestContext(req)
String dirPath = getServletContext().getRea
File dir = new File(dirPath); //just make temp dir manually before hand
int number = dir.list().length;
if(FileUploadBase.isMultip
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory)
try{
out.println("<html>");
out.println("<head><title>
out.println("<body>");
List items = upload.parseRequest(reqCon
FileItem item = (FileItem) items.get(0);
if(item.getSize() < 2000000){
String fileName = item.getName();
int index1 = fileName.lastIndexOf("\\")
if(index1 != -1)fileName = fileName.substring(index1 + 1);
else{
int index2 = fileName.lastIndexOf("/");
if(index2 != -1)fileName = fileName.substring(index1 + 1);
}
int index3 = fileName.lastIndexOf(".");
if(index3 != -1){
fileName = fileName.substring(0,index
+ fileName.substring(index3)
File file = new File(dirPath,fileName);
item.write(file);
out.println("Your file was uploaded to " + file.getName());
}else{
out.println("No file was not uploaded!");
}
}else out.println("File is too big!");
out.println("</body></html
}catch(Exception e){
System.out.println("error"
e.printStackTrace();
}
} else{
out.println("<html>");
out.println("<head><title>
out.println("<body>");
out.println("Problem at server.");
out.println("</body></html
}
}
}
ASKER
If i place two textfields in my jsp and try to run the above servlet it is throwing
NullPointer exception.My jsp looks like this
<html>
<head>
<script>
function uploadfile()
{
form=document.forms[0];
form.action="/fileupload/u pload";
form.submit();
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-da ta">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<font color="blue" size="5">Attach Files</font><br>
Click "Browse" to select a file.You can attach files up to a<br>
total message size of 2.0MB.<br>
File 1:<input type="file" name="file1"/><br>
<input type="button" value="Attach Files" onclick="uploadfile()"/>
</form>
</body>
</html>
NullPointer exception.My jsp looks like this
<html>
<head>
<script>
function uploadfile()
{
form=document.forms[0];
form.action="/fileupload/u
form.submit();
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-da
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<font color="blue" size="5">Attach Files</font><br>
Click "Browse" to select a file.You can attach files up to a<br>
total message size of 2.0MB.<br>
File 1:<input type="file" name="file1"/><br>
<input type="button" value="Attach Files" onclick="uploadfile()"/>
</form>
</body>
</html>
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl oad.disk.D iskFileIte mFactory;
import org.apache.commons.fileupl oad.*;
import org.apache.commons.fileupl oad.servle t.*;
public class leogc3 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti on
{
res.setContentType("text/h tml");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head><title> File Upload</title></head>");
out.println("<body>");
RequestContext reqContext = new ServletRequestContext(req) ;
String dirPath = getServletContext().getRea lPath("/te mp");
File dir = new File(dirPath); //just make temp dir manually before hand
int number = dir.list().length;
if(FileUploadBase.isMultip artContent (reqContex t)){
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory) ;
List items = null;
try{
items = upload.parseRequest(reqCon text);
} catch(FileUploadException fue){throw new ServletException(fue);}
FileItem item = null;
for (int i = 0; i < items.size(); i ++) {
item = (FileItem) items.get(i);
if(item.isFormField()){
String fieldName = item.getFieldName();
if("name".equals(fieldName )){
out.println("name=" + item.getString());
}
if("email".equals(fieldNam e)){
out.println("email=" + item.getString());
}
}else{
if(item.getSize() < 2000000){
String fileName = item.getName();
int index1 = fileName.lastIndexOf("\\") ;
if(index1 != -1)fileName = fileName.substring(index1 + 1);
else{
int index2 = fileName.lastIndexOf("/");
if(index2 != -1)fileName = fileName.substring(index1 + 1);
}
int index3 = fileName.lastIndexOf(".");
if(index3 != -1){
fileName = fileName.substring(0,index 3) + number
+ fileName.substring(index3) ;
File file = new File(dirPath,fileName);
try{
item.write(file);
}catch(Exception e){throw new ServletException(e);}
out.println("Your file was uploaded to " + file.getName());
}else out.println("No file was not uploaded!");
}else out.println("File is too big!");
}
}
}else{
out.println("Problem with upload!");
}
out.println("</body></html >");
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupl
import org.apache.commons.fileupl
import org.apache.commons.fileupl
public class leogc3 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOExcepti
{
res.setContentType("text/h
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head><title>
out.println("<body>");
RequestContext reqContext = new ServletRequestContext(req)
String dirPath = getServletContext().getRea
File dir = new File(dirPath); //just make temp dir manually before hand
int number = dir.list().length;
if(FileUploadBase.isMultip
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory)
List items = null;
try{
items = upload.parseRequest(reqCon
} catch(FileUploadException fue){throw new ServletException(fue);}
FileItem item = null;
for (int i = 0; i < items.size(); i ++) {
item = (FileItem) items.get(i);
if(item.isFormField()){
String fieldName = item.getFieldName();
if("name".equals(fieldName
out.println("name=" + item.getString());
}
if("email".equals(fieldNam
out.println("email=" + item.getString());
}
}else{
if(item.getSize() < 2000000){
String fileName = item.getName();
int index1 = fileName.lastIndexOf("\\")
if(index1 != -1)fileName = fileName.substring(index1 + 1);
else{
int index2 = fileName.lastIndexOf("/");
if(index2 != -1)fileName = fileName.substring(index1 + 1);
}
int index3 = fileName.lastIndexOf(".");
if(index3 != -1){
fileName = fileName.substring(0,index
+ fileName.substring(index3)
File file = new File(dirPath,fileName);
try{
item.write(file);
}catch(Exception e){throw new ServletException(e);}
out.println("Your file was uploaded to " + file.getName());
}else out.println("No file was not uploaded!");
}else out.println("File is too big!");
}
}
}else{
out.println("Problem with upload!");
}
out.println("</body></html
}
}
ASKER
The fileupload part is working correctly now.Thanks for the reply.Now i want to store the original file path and the renamed file path in database so that it can be
retrieved later.Any inputs of how to do this will be helpful.
regards
leo
retrieved later.Any inputs of how to do this will be helpful.
regards
leo
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
The maximum file size can be set along with other settings in the receiving servlet
-----------
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(y
factory.setRepositoryPath(
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory)
// Set overall request size constraint -- HERE
upload.setSizeMax(yourMaxR
// Parse the request
List /* FileItem */ items = upload.parseRequest(reques