Solved

How can I upload file to desired directory in JSP ?

Posted on 2004-03-29
12
877 Views
Last Modified: 2012-06-27
Dear experts,
  How can I upload files to desired directory using JSP ? Does anyone of you can show my some example or source of code ? Thx so much.

0
Comment
Question by:duckywong
  • 4
  • 2
  • 2
  • +4
12 Comments
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10703218
0
 
LVL 6

Expert Comment

by:jarasa
ID: 10704716
Use this:

Upload.jsp
<%@ page errorPage="ErrorUpload.jsp" %>
<jsp:useBean id="prop" scope="page" class="java.util.Properties" />
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.servlet.*" %>
<%!
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;        
}
%>
<%
      // Here you can put the path you want
      String DPATH = "C:\\jakarta4\\webapps\\Root\\VW02\\Motivacion\\Programa\\upload\\";
      int  ROUGHSIZE=1024;
      int  MAXSIZE  =  10; // Mega Byte
      String boundary = getBoundary(request,prop);
      if( boundary == null ){
            boundary = prop.getProperty("boundary");// This statement line for HOTJAVABROWSER 3.0
      }else{
            boundary = "--"+boundary;
      }
      if( boundary == null ){
      
            throw new Exception("BNF");
      }
      // out.println("Content-length:\t"+prop.getProperty("content-length","0"));
      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;
      /*
            You can restrict upload file size in the following way
          1. after uploaded u cannt find out file size then display error message
            2. from contentsize it will give approximate size of file in bytes.
               based on this u can restrict uploading.
      */
      int KB = 1024;
      int MB = 1024 * KB;
      int csize = (int)(l / MB);
      if( csize > MAXSIZE ){
            throw new Exception("EL");
      }
      
      
      ServletInputStream fin =  request.getInputStream();
      // Geting 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");
      }
      for( long i = 0L; i < l ; i++){
            c = fin.read();
            if( c == -1 ) break;
            fout.write(c);
      }
      
      if( c != -1 ){
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while(  (c = fin.read()) != -1 ){
                  baos.write(c);
            }
            String laststring = baos.toString();
            int idx = laststring.indexOf(boundary);
            byte 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();
%>
<html>
<body bgcolor="#000066" text="#0099FF">
<blockquote>&nbsp;</blockquote>
<div align="center">
  <TABLE>
    <TR>
      <th width="152">
        <div align="left"><font face="Arial, Helvetica, sans-serif">Fichero enviado:</font></div>
      </th>
      <TD width="189"><B><%=newfile.getName()%></B></TD>
    </TR>
    <TR>
      <th width="152">
        <div align="left"><font face="Arial, Helvetica, sans-serif">Tamaño:</font></div>
      </th>
      <TD width="189"><B><%=newfile.length()%>Kb</B></TD>
    </TR>
  </TABLE>
</div>
</body>
</html>

ErrorUpload.jsp
<%@ page isErrorPage="true" %>
<html>
<body bgcolor="#000066" text="#0099FF">
<h1>
<%     if( exception.getMessage().equals("BNF") ){
            out.println("Boundary not found in Content-type");
         }
         else if(exception.getMessage().equals("ZERO") ){
                out.println("Could not find out Content Size");
         }
         else if(exception.getMessage().equals("BBNF") ){
                out.println("Begin Boundary  not found");
         }
         else if(exception.getMessage().equals("FNF") ){
                out.println("Please select file / Problem in File Creation in Server");
         }
         else if(exception.getMessage().equals("EL") ){
            out.println("U R Uploading exceed user limt");
         }
         else if(exception.getMessage().equals("EBNF") ){
            out.println("Please check out upload file path");
         }
         else{
            out.println(exception.getMessage());                  
         }
%>
</h1>               
      
</body>
</html>
       

Javier
0
 
LVL 6

Expert Comment

by:jarasa
ID: 10704736
I forgot to tell you how to put the link on the HTML

<form name="Test" method="post" action="Upload.jsp" enctype="multipart/form-data">
......
</form>


Javier
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 14

Expert Comment

by:kennethxu
ID: 10705443
check out struts, it comes with a sample application that does the file upload.
0
 
LVL 92

Expert Comment

by:objects
ID: 10708336
0
 
LVL 2

Expert Comment

by:vikram_1982
ID: 10711434
<%@ page import = "java.io.*" %>
<%
//The directory where the uploaded file should be stored
String savePath = "D:\\Images\\";  //This folder should be present.. A new folder will NOT be
//created if it is not already present
String filename = "";

ServletInputStream in = request.getInputStream();

byte[] line = new byte[128];
int i = in.readLine(line,0,128);
int boundaryLength = i-2;
String boundary = new String(line,0,boundaryLength);
// -2 discards the newline character

while(i!=-1)
{
      String newLine = new String(line,0,i);
      if(newLine.startsWith("Content-Disposition: form-data; name=\""))
      {
            String s = new String (line,0,i-2);
            int pos = s.indexOf("filename=\"");
            if (pos != -1)
            {
                  String filepath = s.substring(pos+10,s.length()-1);
                  pos = filepath.lastIndexOf("\\");
                  if(pos != -1)
                  {
                        filename = filepath.substring(pos+1);
                  }
                  else
                  {
                        filename = filepath;
                  }
            }
            
            //this is the file content
            
            i = in.readLine(line,0,128);
            i = in.readLine(line,0,128);
            //Blank Line
            i = in.readLine(line,0,128); //Check the model output file
            
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            newLine = new String(line,0,i);
            
            while (i != -1 && !newLine.startsWith(boundary))
            {
                  //The last line of the file content contains the new line character
                  //so we need to check if the line that we are currently reading is infact
                  //the last line or not.
                  
                  buffer.write(line,0,i);
                  i = in.readLine(line,0,128);
                  newLine = new String(line,0,i);
            }
            
            try
            {
                  //save the uploaded file
                  
                  RandomAccessFile f = new RandomAccessFile(savePath + filename, "rw");
                  byte[] bytes = buffer.toByteArray();
                  f.write(bytes,0,bytes.length - 2);
                  f.close();
            }
            catch(Exception e)
            {}
      }
      i=in.readLine(line,0,128);
}
%>
<html>
<head>
<title>File Uploaded....</title>
</head>

<body>

</body>
</html>
0
 

Author Comment

by:duckywong
ID: 10711887
If the directory is at the remote (server) side ? What should I do ?
0
 
LVL 6

Expert Comment

by:jarasa
ID: 10712042
What you mean, you want to upload the file to a different machine that the Webserver??

The JSP has to be on the Server Machine so the Path you put is from the machine, if you want to send it to a different one there are two ways, you have that machine as network drive G: \\MACHINE\RESOURCE or you do it via FTP but I do not recomend you that.

Javier
0
 
LVL 2

Expert Comment

by:vikram_1982
ID: 10721226
u mean to say that u do not have direct access to the place where the files are stored?? The jsp file is generally placed in the server. So maybe you could specify the location where the file has to be uploaded relative to the location where the jsp file is placed
0
 
LVL 6

Accepted Solution

by:
jarasa earned 500 total points
ID: 10721851
Yes you can do it relatively or with the full path. But always to that machine not to a diferent one.
0
 

Expert Comment

by:arthurwang
ID: 14704737
hi, every experts, I want to upload file to either the web server machine or a different machine from application server machine, how can I do that? please look at my post here:

http://www.experts-exchange.com/Web/Application_Servers/Q_21531664.html

since I have two application server located in two seperated machine for load balance, and web server is located in the third machine,  I want to put the uploaded file at any machine where the apache web server can find it  but except the two applaication server machine which host Jboss server each.
0
 

Expert Comment

by:arthurwang
ID: 14704749
sorry, some typo on my post:

I want to upload file to either the web server machine or a different machine other than application server machine
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Starting your own business is always a daunting process, and for most people it is brand new experience. Avoid the common pitfalls by following these tips to start on the road to success.
When it comes to protecting Oracle Database servers and systems, there are a ton of myths out there. Here are the most common.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question