p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


Go Back   p2p.wrox.com Forums > Java > Java and JDK > JSP Basics
I forgot my password Register Now
Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
JSP Basics Beginning-level questions on JSP. More advanced coders should post to Pro JSP.

Welcome to the p2p.wrox.com Forums.

You are currently viewing the JSP Basics section of the Wrox p2p Programmer to Programmer discussion community. This is a community of more than 40,000 computer programmers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining our free Wrox p2p community you can post your own programming questions and respond to other programmers’ questions. Registered users also don't have to see the ads that are displayed to guests. Registration is fast, simple and absolutely free so please, join today!
Join today and post to win prizes! Post more to increase your chances of being Wrox’s top poster of the month.

Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old May 5th, 2005, 08:31 AM
Registered User
 
Join Date: May 2005
Location: , , Hong Kong.
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via ICQ to chitocheng
Default How to upload file in JSP

I'm going to set up a simple jsp which allow user the upload file. But I have not idea how the jsp syntax should be. If my html from is as follow:

<form type="post" action="upload.jsp">
    <input type="file" name="upfile">
</form>

then how the upload.jsp should be?
I just want to save the file in the same directory of the jsp.

Pls help

CCT
__________________
CCT
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Reddit!
Reply With Quote
  #2 (permalink)  
Old February 2nd, 2007, 12:22 PM
Registered User
 
Join Date: Jan 2007
Location: , , Philippines.
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Default

UPLOAD.JSP
<%

    response.setContentType("text/html");
    response.setHeader("Cache-control","no-cache");

    String err = "";

    String lastFileName = "";

    String contentType = request.getContentType();
    String boundary = "";
    final int BOUNDARY_WORD_SIZE = "boundary=".length();
    if(contentType == null || !contentType.startsWith("multipart/form-data")) {
      err = "Ilegal ENCTYPE : must be multipart/form-data\n";
      err += "ENCTYPE set = " + contentType;
    }else{
      boundary = contentType.substring(contentType.indexOf("boundar y=") + BOUNDARY_WORD_SIZE);
      boundary = "--" + boundary;
      try {
        javax.servlet.ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[1024];
        int x=0;
        int state=0;
        String name=null,fileName=null,contentType2=null;
        java.io.FileOutputStream buffer = null;
        while((x=sis.readLine(b,0,1024))>-1) {
          String s = new String(b,0,x);
          if(s.startsWith(boundary)) {
            state = 0;
            //out.println("name="+name+"<br>");
            //out.println(fileName+"<br>");

            name = null;
            contentType2 = null;
            fileName = null;


          }else if(s.startsWith("Content-Disposition") && state==0) {
            state = 1;
            if(s.indexOf("filename=") == -1)
              name = s.substring(s.indexOf("name=") + "name=".length(),s.length()-2);
            else {
              name = s.substring(s.indexOf("name=") + "name=".length(),s.lastIndexOf(";"));
              fileName = s.substring(s.indexOf("filename=") + "filename=".length(),s.length()-2);
              if(fileName.equals("\"\"")) {
                fileName = null;
              }else {
                String userAgent = request.getHeader("User-Agent");
                String userSeparator="/"; // default
                if (userAgent.indexOf("Windows")!=-1)
                  userSeparator="\\";
                if (userAgent.indexOf("Linux")!=-1)
                  userSeparator="/";
                fileName = fileName.substring(fileName.lastIndexOf(userSepara tor)+1,fileName.length()-1);
                if(fileName.startsWith( "\""))
                  fileName = fileName.substring( 1);
              }
            }
            name = name.substring(1,name.length()-1);
            if (name.equals("file")) {
              if (buffer!=null)
                buffer.close();
              lastFileName = fileName;
              buffer = new java.io.FileOutputStream("/Program Files/Apache SOftware Foundation/Tomcat 5.0/webapps/ROOT/Upload/"+fileName);
            }
          }else if(s.startsWith("Content-Type") && state==1) {
            state = 2;
            contentType2 = s.substring(s.indexOf(":")+2,s.length()-2);
          }else if(s.equals("\r\n") && state != 3) {
            state = 3;
          }else {
            if (name.equals("file"))
              buffer.write(b,0,x);
          }
        }
        sis.close();
        buffer.close();
      }catch(java.io.IOException e) {
        err = e.toString();
      }
    }
    boolean ok = err.equals("");
    if(!ok) {
      out.println(err);
    }else{
    String fn=lastFileName;
  try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection ("jdbc:odbc:fapotc");
            PreparedStatement ps = con.prepareStatement ("Insert into downloads values(?)");
            ps.setString(1,fn);
            ps.executeUpdate();
            ps.close();
            con.close();
        }
            catch (Exception e)
            {
            out.println(e);
            }
            //response.sendRedirect(".jsp");
    %>
<SCRIPT language="javascript">
  history.back(1)
  alert('Uploaded <%=lastFileName%>');
  window.location.reload(false)
</SCRIPT>
    <%
    }
    out.println("done");
%>

---

UPLOAD.HTM

<form name="uploadForm" action="uploding.jsp" enctype="multipart/form-data" method="post">
  <input type="file" name="file"/>
  <input TYPE=Button name='Upload' Value='Upload' onClick="uploadForm.Upload.value='Uploading...';do cument.uploadForm.action='uploding.jsp';document.u ploadForm.submit()">
</form>



Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Reddit!
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
hi have to upload excel file using jsp uttam.mca Pro JSP 3 July 14th, 2006 08:30 PM
sample JSP to upload file to database rahulsaxena Pro JSP 2 January 16th, 2006 05:59 AM
JSP file upload and delete file pandjie JSP Basics 0 January 29th, 2005 10:49 PM
upload doc,pdf file from ORACLE 9i on JSP page ashwinmittal Pro JSP 1 November 30th, 2004 01:18 PM
File Upload in JSP jenty_c Pro JSP 3 October 1st, 2004 08:56 AM



All times are GMT -4. The time now is 07:40 AM.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
© 2008 Wiley Publishing, Inc