Solved

uploading binary files in jsp

Posted on 2001-08-02
10
303 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 

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
 

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
JDeveloper 12c for 32 bit 4 84
sites similar to codingbat to improve coding hanson skills 3 49
stackato and cloud 4 85
Android development question 2 35
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

786 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