uploading binary files in jsp

How i do i upload binary files on to the server using an html form ? Could anybody provide me with the source for this ? Thanx in advance..............
nitin_bahriAsked:
Who is Participating?
 
anhphuongnnCommented:
Hi nitin_bahri,

This simple is tested.
Wrote by servlet.
File will be upload into c:\Temp folder

"UploadFile.html"

<html>
<body bgcolor="#ffffff">
<TABLE align=left border=0 cellPadding=0 cellSpacing=0 width=785>

    <TR>
        <TD colSpan=3></TD>
    </TR></TR>
    <TR>
        <TD></TD>
        <TD valign="top">
      <!-- Begin Contents -->
      <FORM action="http://localhost:8080/examples/servlet/UploadTextFile" method=post       ENCTYPE="multipart/form-data">
<p valign=center><h2><FONT color=#666699 face=".vnTime" size=6>Upload Files</FONT></h2></p>
<TABLE border=0 cellPadding=0 cellSpacing=0>
    <TR>
        <TD><INPUT id=file name="filename" type=file ></TD>
      </TR>
    <TR>
        <TD><INPUT id=button1 name=button1 type=submit value=Upload></TD>
    </TR>
</TABLE>
</FORM>
      <!-- End Contents -->
      </TD>
        <TD></TD></TR>
    <TR>
        <TD rowSpan=2></TD>
        <TD></TD>
        <TD></TD></TR></TABLE>

</body></HTML>


Java servlet code.

UploadTextFile.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class UploadTextFile extends HttpServlet {

      public void init(ServletConfig config)throws ServletException  {
       super.init(config);
      }

   public void service(HttpServletRequest request,HttpServletResponse response)
                                throws ServletException, IOException {
      String _fileName = null;
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<html><body>");

      if (request.getMethod().equals("POST")
            && request.getContentType().startsWith("multipart/form-data"))
            {
            int index = request.getContentType().indexOf("boundary=");
            if (index < 0) {
                   out.println("can't find boundary type");
            return;
            }

            String boundary = request.getContentType().substring(index+9);
            ServletInputStream instream = request.getInputStream();
            byte[] tmpbuffer = new byte[8600];
            int length=0;
            String inputLine=null;
            boolean moreData=true;

         //Skip until form data is reached
       length = instream.readLine(tmpbuffer,0, tmpbuffer.length);
       inputLine = new String (tmpbuffer, 0,length);

       while(inputLine.indexOf(boundary)>0 && moreData) {
         length = instream.readLine(tmpbuffer,0,tmpbuffer.length);
         inputLine = new String (tmpbuffer,0,length);

         if(length<0)
             moreData=false;

       }

               if(moreData) {
                  //cut once boundary
                  if(inputLine.indexOf("filename") >=0) {
                        int startindex=inputLine.lastIndexOf("filename");
                        _fileName = inputLine.substring(startindex+10, inputLine.indexOf("\"",startindex+11)) ;
                        _fileName = _fileName.substring(_fileName.lastIndexOf("\\")+1,_fileName.length());
                        //read content text
                        length = instream.readLine(tmpbuffer,0,tmpbuffer.length);
                        inputLine = new String (tmpbuffer,0,length);

                  }

         }//more data

         byte fileBytes[]=new byte[50000];
         int offset=0;


         if (moreData)
         try{

           while(moreData) {
             length = instream.readLine(tmpbuffer,0,tmpbuffer.length);
             inputLine = new String (tmpbuffer,0, length);
                  if(length>0 && (inputLine.indexOf(boundary) <0)){
                     System.arraycopy(tmpbuffer,0,fileBytes,offset,length);
               offset+=length;
            }else
                   moreData = false;
           }

        }catch (IOException ex){
                out.println("IOexcepton: " + ex.getMessage());
        };
       byte realFileBytes[]=new byte[offset-2];
       for(int i=0;i<offset-2;i++) {
            realFileBytes[i] = fileBytes[i];

        }

            //create file
            FileOutputStream       file_out        = null;
            File                         file_outName = null;

            try
            {

                  file_outName = new File ("c:\\Temp" + file_outName.separator + _fileName);
                  file_out = new FileOutputStream (file_outName);
                  file_out.write (realFileBytes);

                  file_out.close();
                  //response.sendRedirect("AddListUpload.Html");
                  out.println("<font color =red>Upload OK</font>");
            }
            catch (Exception      ex)
            {
                   out.println("Error when create");
            }
            //end create file

     }//end while

     out.println("</body></html>");
     out.close();
  }
}



PhuongNguyen
0
 
SendohCommented:
hi !!
check out this site for the uploa servlet...

http://www.servlets.com/cos/index.html

hope it helps. :)
0
 
nitin_bahriAuthor Commented:
Hi PhuongNguyen,
                  Thanx...The code works fine for files of size upto 30kb. But whenever i try to upload a file, say of about 50kb or more i get an error msg which goes something like this:

java.lang.ArrayIndexOutOfBoundsException
     at java.lang.System.arraycopy(Native Method)
     at UploadTextFile.service(UploadTextFile.java:73)
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
     at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1416)
     at allaire.jrun.session.JRunSessionService.service(../session/JRunSessionService.java:1082)
     at allaire.jrun.servlet.JRunSE.runServlet(../servlet/JRunSE.java:1270)
     at allaire.jrun.servlet.JRunNamedDispatcher.forward(../servlet/JRunNamedDispatcher.java:39)
     at allaire.jrun.servlet.Invoker.service(../servlet/Invoker.java:84)
     at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1416)
     at allaire.jrun.session.JRunSessionService.service(../session/JRunSessionService.java:1082)
     at allaire.jrun.servlet.JRunSE.runServlet(../servlet/JRunSE.java:1270)
     at allaire.jrun.servlet.JRunRequestDispatcher.forward(../servlet/JRunRequestDispatcher.java:89)
     at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1552)
     at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1542)
     at allaire.jrun.servlet.JvmContext.dispatch(../servlet/JvmContext.java:364)
     at allaire.jrun.http.WebEndpoint.run(../http/WebEndpoint.java:115)
     at allaire.jrun.ThreadPool.run(../ThreadPool.java:272)
     at allaire.jrun.WorkerThread.run(../WorkerThread.java:75)

Please help me on this. I want to upload images say of around 500 kb or so.
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
anhphuongnnCommented:
hi

Can you try again with tmpbuffer size > 8600
byte[] tmpbuffer = new byte[8600];

PhuongNguyen

0
 
anhphuongnnCommented:
Hi

Sorry you change in here
i'm tried this ok
byte fileBytes[]=new byte[500000];//50000];


still keep th same old code
byte[] tmpbuffer = new byte[860];



PhuongNguyen

0
 
nitin_bahriAuthor Commented:
Dear PhuongNguyen

The file upload servlet gives the message that the file has been successfully uploaded. But when i try to open the file inthe browser, its not opening. What could be the reason for this. Please let me know. thanx.......

Nitin
0
 
anhphuongnnCommented:
Hi nitin_bahri,

You insert new lines after those line in the code.
byte fileBytes[]=new byte[2048576];//50000];
int offset=0;

//Add new those lines
length = instream.readLine(tmpbuffer,0,tmpbuffer.length);
inputLine = new String (tmpbuffer,0, length);

That running well.

PhuongNguyen


0
 
anhphuongnnCommented:
Hi nitin_bahri,

You insert new lines after those line in the code.
byte fileBytes[]=new byte[2048576];//50000];
int offset=0;

//Add new those lines
length = instream.readLine(tmpbuffer,0,tmpbuffer.length);
inputLine = new String (tmpbuffer,0, length);

That running well.

PhuongNguyen


0
 
anhphuongnnCommented:
HI,

WHERE ARE YOU?

PhuongNguyen
0
 
nitin_bahriAuthor Commented:
Thanx friend
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.