Solved

uploading binary files in jsp

Posted on 2001-08-02
10
300 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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

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…
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…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

760 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

21 Experts available now in Live!

Get 1:1 Help Now