Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > Java > Java and JDK > JSP Basics
Password Reminder
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 Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old May 5th, 2005, 07: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
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>



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

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


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 07: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 07:56 AM



All times are GMT -4. The time now is 05:54 AM.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.