Solved

How can I upload file to desired directory in JSP ?

Posted on 2004-03-29
12
875 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
trouble with PDF encryption using itext-1.3.1 17 82
Display the newly inserted values 3 74
Fisheye tool 2 104
console vs log file 16 77
Microsoft Office Picture Manager was included in Office 2003, 2007, and 2010, but not in Office 2013. Users had hopes that it would be in Office 2016/Office 365, but it is not. Fortunately, the same zero-cost technique that works to install it with …
We need a new way to communicate time sensitive or critical info.   The best part of my role at xMatters is visiting our clients all over the world to learn about how they operate their businesses, share insights that xMatters has gleaned across…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

867 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now