Solved

uploading binary files in jsp

Posted on 2001-08-02
10
306 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
ejb wildfly example 2 72
eclipse console opening separately 2 37
jmeter usage 4 35
learn programming 8 68
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
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:

756 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