Solved

uploading binary files in jsp

Posted on 2001-08-02
10
301 Views
Last Modified: 2010-03-31
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..............
0
Comment
Question by:nitin_bahri
  • 6
  • 3
10 Comments
 
LVL 3

Expert Comment

by:Sendoh
ID: 6344055
hi !!
check out this site for the uploa servlet...

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

hope it helps. :)
0
 

Accepted Solution

by:
anhphuongnn earned 50 total points
ID: 6347580
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
 

Author Comment

by:nitin_bahri
ID: 6347715
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
 

Expert Comment

by:anhphuongnn
ID: 6347810
hi

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

PhuongNguyen

0
 

Expert Comment

by:anhphuongnn
ID: 6347861
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
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:nitin_bahri
ID: 6348113
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
 

Expert Comment

by:anhphuongnn
ID: 6354664
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
 

Expert Comment

by:anhphuongnn
ID: 6354675
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
 

Expert Comment

by:anhphuongnn
ID: 6366876
HI,

WHERE ARE YOU?

PhuongNguyen
0
 

Author Comment

by:nitin_bahri
ID: 6367110
Thanx friend
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
Which is the latest version of Apache Tomcatl 3 50
unix in java example 9 53
Checkbox and ListView in Android Layout 4 56
Strange loading of website behaviour 3 32
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

862 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

24 Experts available now in Live!

Get 1:1 Help Now