Several common file upload in jsp and struts Methods

sponsored links
Upload files using FileUpload Component

File upload in web applications are very common in the environment to achieve jsp file upload feature is very easy, because there are many web development with java file upload component, this paper commons-fileupload component, for example, is Add file upload jsp application.
common-fileupload component is an open source one of apache, you can download from the http://jakarta.apache.org/commons/fileupload/. The component can be achieved with one or more files once uploaded, and can limit the file size.
You must extract the zip package, commons-fileupload-1.0.jar will be copied to tomcat's webapps \ your webapp \ WEB-INF \ lib \, the directory does not exist, please self-built directory.
Create a new servlet: Upload.java for file uploads:

Java code
  1. public class Upload extends HttpServlet {
  2. private String uploadPath = "C: \ \ upload \ \"; / / upload files
  3. private String tempPath = "C: \ \ upload \ \ tmp \ \"; / / temporary file directory
  4. public void doPost (HttpServletRequest request,
  5. HttpServletResponse response)
  6. throws IOException, ServletException
  7. {
  8. }
  9. }
  10. In the doPost () method, when the servlet receives a browser request issued by the Post, the implementation file upload. The following is a sample code:
  11. public void doPost (HttpServletRequest request,
  12. HttpServletResponse response)
  13. throws IOException, ServletException
  14. {
  15. try {
  16. DiskFileUpload fu = new DiskFileUpload ();
  17. / / Set the maximum file size, here is the 4MB
  18. fu.setSizeMax (4194304);
  19. / / Set the buffer size, this is 4kb
  20. fu.setSizeThreshold (4096);
  21. / / Set the temporary directory:
  22. fu.setRepositoryPath (tempPath);
  23. / / Get all the files:
  24. List fileItems = fu.parseRequest (request);
  25. Iterator i = fileItems.iterator ();
  26. / / Process each file in turn:
  27. while (i.hasNext ()) {
  28. FileItem fi = (FileItem) i.next ();
  29. / / Get the file name, the file name including the path:
  30. String fileName = fi.getName ();
  31. / / Here the user can record and file information
  32. / / ...
  33. / / Write to file, the file named interim a.txt, can be extracted from the file name fileName:
  34. fi.write (new File (uploadPath + "a.txt"));
  35. }
  36. }
  37. catch (Exception e) {
  38. / / Error page you can jump
  39. }
  40. }
  41. If you want to read the configuration file specified in the upload folder in the init () method implementation:
  42. public void init () throws ServletException {
  43. uploadPath = ....
  44. tempPath = ....
  45. / / Folder does not exist are automatically created:
  46. if (! new File (uploadPath). isDirectory ())
  47. new File (uploadPath). mkdirs ();
  48. if (! new File (tempPath). isDirectory ())
  49. new File (tempPath). mkdirs ();
  50. }

public class Upload extends HttpServlet {

    private String uploadPath = "C:\\upload\\"; //   Upload files  
    private String tempPath = "C:\\upload\\tmp\\"; //   Temporary file directory  

    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException
    {
    }
}
  In doPost()  Method, when  servlet  Post received the browser request issued  ,  For file uploads. The following is a sample code  :
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
    try {
        DiskFileUpload fu = new DiskFileUpload();
        //   Set the maximum file size, this is  4MB
        fu.setSizeMax(4194304);
        //   Set the buffer size, this is  4kb
        fu.setSizeThreshold(4096);
        //   Temporary directory  :
        fu.setRepositoryPath(tempPath);

        //   Get all the files  :
        List fileItems = fu.parseRequest(request);
        Iterator i = fileItems.iterator();
        //   Processes each file in turn  :
        while(i.hasNext()) {
            FileItem fi = (FileItem)i.next();
            //   Access to the file name, the file name including path  :
            String fileName = fi.getName();
            //   Here you can record the user and file information  
            // ...
            //   Written to the file, the file named interim  a.txt,  Can be extracted from the file name fileName  :
            fi.write(new File(uploadPath + "a.txt"));
        }
    }
    catch(Exception e) {
        //   Error page can jump  
    }
}
 If you want to read the configuration file specified in the upload folder, you can  init()  Method of execution  :
public void init() throws ServletException {
    uploadPath = ....
    tempPath = ....
    //   Folder does not exist to automatically create  :
    if(!new File(uploadPath).isDirectory())
        new File(uploadPath).mkdirs();
    if(!new File(tempPath).isDirectory())
        new File(tempPath).mkdirs();
}






Compile the servlet, note to specify classpath, be sure to include commons-upload-1.0.jar and the tomcat \ common \ lib \ servlet-api.jar.
Configuration servlet, use Notepad to open the tomcat \ webapps \ your webapp \ WEB-INF \ web.xml, if not, create a new one.
A typical configuration is as follows:

Web.xml code
  1. <? Xml version = "1.0" encoding = "ISO-8859-1"?>
  2. <! DOCTYPE web-app
  3. PUBLIC "- / / Sun Microsystems, Inc. / / DTD Web Application 2.3 / / EN"
  4. "Http://java.sun.com/dtd/web-app_2_3.dtd">
  5. <web-app>
  6. <servlet>
  7. <servlet-name> Upload </ servlet-name>
  8. <servlet-class> Upload </ servlet-class>
  9. </ Servlet>
  10. <servlet-mapping>
  11. <servlet-name> Upload </ servlet-name>
  12. <url-pattern> / fileupload </ url-pattern>
  13. </ Servlet-mapping>
  14. </ Web-app>

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <servlet>
        <servlet-name>Upload</servlet-name>
        <servlet-class>Upload</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Upload</servlet-name>
        <url-pattern>/fileupload</url-pattern>
    </servlet-mapping>
</web-app>




Configured servlet, start the tomcat, write a simple html test:

Struts Code
  1. <Form action = "fileupload" method = "post"
  2. enctype = "multipart / form-data" name = "form1">
  3. <input type="file" name="file">
  4. <input type="submit" name="Submit" value="upload">
  5. </ Form>

<form action="fileupload" method="post"
enctype="multipart/form-data" name="form1">
  <input type="file" name="file">
  <input type="submit" name="Submit" value="upload">
</form>

Note that action = "fileupload" which fileupload servlet is configured when the specified url-pattern.

II:
Select upload page: selfile.jsp, so visit this page:

Jsp code
  1. <html:link module="/upload" page="/upload.do"> continue to upload </ html: link> </ h2>
  2. -------------------------------------------------- ------------------------------
  3. <% @ Page contentType = "text / html; charset = GBK"%>
  4. <% @ Page import = "org.apache.struts.action .*,
  5. java.util.Iterator,
  6. org.apache.struts.Globals "%>
  7. <% @ Taglib uri = "/ tags / struts-bean" prefix = "bean"%>
  8. <% @ Taglib uri = "/ tags / struts-html" prefix = "html"%>
  9. <% @ Taglib uri = "/ tags / struts-logic" prefix = "logic"%>
  10. <logic:messagesPresent>
  11. <ul>
  12. <html:messages>
  13. <li> <bean:write name="error"/> </ li>
  14. </ Html: messages>
  15. </ Ul> <hr />
  16. </ Logic: messagesPresent>
  17. <html:html>
  18. <html:form action="uploadsAction.do" enctype="multipart/form-data">
  19. <html:file property="theFile"/>
  20. <html:submit/>
  21. </ Html: form>
  22. </ Html: html>

<html:link module="/upload" page="/upload.do">   Continue to upload  </html:link></h2> 

-------------------------------------------------------------------------------- 
<%@ page contentType="text/html; charset=GBK" %> 
<%@ page import="org.apache.struts.action.*, 
                 java.util.Iterator, 
                 org.apache.struts.Globals" %> 
<%@ taglib uri="/tags/struts-bean" prefix="bean" %> 
<%@ taglib uri="/tags/struts-html" prefix="html" %> 
<%@ taglib uri="/tags/struts-logic" prefix="logic" %> 
<logic:messagesPresent> 
   <ul> 
   <html:messages> 
      <li><bean:write name="error"/></li> 
   </html:messages> 
   </ul><hr /> 
</logic:messagesPresent> 
<html:html> 

<html:form action="uploadsAction.do" enctype="multipart/form-data"> 
<html:file property="theFile"/> 
<html:submit/> 
</html:form> 
</html:html> 


Form bean: UpLoadForm.java

Java code
  1. package org.apache.struts.webapp.upload;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.apache.struts.action .*;
  4. import org.apache.struts.upload .*;
  5. / **
  6. * <p> Title: UpLoadForm </ p>
  7. * <p> Description: QRRSMMS </ p>
  8. * <p> Copyright: Copyright (c) 2004 jiahansoft </ p>
  9. * <p> Company: jiahansoft </ p>
  10. * @ Author wanghw
  11. * @ Version 1.0
  12. * /
  13. public class UpLoadForm extends ActionForm {
  14. public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "org.apache.struts.webapp.upload.MaxLengthExceeded";
  15. protected FormFile theFile;
  16. public FormFile getTheFile () {
  17. return theFile;
  18. }
  19. public void setTheFile (FormFile theFile) {
  20. this. theFile = theFile;
  21. }
  22. public ActionErrors validate (
  23. ActionMapping mapping,
  24. HttpServletRequest request) {
  25. ActionErrors errors = null;
  26. / / Has the maximum length been exceeded?
  27. Boolean maxLengthExceeded =
  28. (Boolean) request.getAttribute (
  29. MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
  30. if ((maxLengthExceeded! = null) & & (maxLengthExceeded.booleanValue ())) {
  31. errors = new ActionErrors ();
  32. errors.add (
  33. ActionMessages.GLOBAL_MESSAGE,
  34. new ActionMessage ("maxLengthExceeded"));
  35. errors.add (
  36. ActionMessages.GLOBAL_MESSAGE,
  37. new ActionMessage ("maxLengthExplanation"));
  38. }
  39. return errors;
  40. }
  41. }

package org.apache.struts.webapp.upload; 
import javax.servlet.http.HttpServletRequest; 
import org.apache.struts.action.*; 
import org.apache.struts.upload.*; 

/** 
 * <p>Title:UpLoadForm</p> 
 * <p>Description: QRRSMMS </p> 
 * <p>Copyright: Copyright (c) 2004 jiahansoft</p> 
 * <p>Company: jiahansoft</p> 
 * @author wanghw 
 * @version 1.0 
 */ 

public class UpLoadForm extends ActionForm { 
  public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "org.apache.struts.webapp.upload.MaxLengthExceeded"; 
  protected FormFile theFile; 
  public FormFile getTheFile() { 
      return theFile; 
  } 
  public void setTheFile(FormFile theFile) { 
      this.theFile = theFile; 
  } 
   public ActionErrors validate( 
        ActionMapping mapping, 
        HttpServletRequest request) { 
             
        ActionErrors errors = null; 
        //has the maximum length been exceeded? 
        Boolean maxLengthExceeded = 
            (Boolean) request.getAttribute( 
                MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED); 
                 
        if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) { 
            errors = new ActionErrors(); 
            errors.add( 
                ActionMessages.GLOBAL_MESSAGE , 
                new ActionMessage("maxLengthExceeded")); 
            errors.add( 
                ActionMessages.GLOBAL_MESSAGE , 
                new ActionMessage("maxLengthExplanation")); 
        } 
        return errors; 

    } 

} 


Handling uploaded files: UpLoadAction.java

Java code
  1. package org.apache.struts.webapp.upload;
  2. import java.io. *;
  3. import javax.servlet.http .*;
  4. import org.apache.struts.action .*;
  5. import org.apache.struts.upload.FormFile;
  6. / **
  7. * <p> Title: UpLoadAction </ p>
  8. * <p> Description: QRRSMMS </ p>
  9. * <p> Copyright: Copyright (c) 2004 jiahansoft </ p>
  10. * <p> Company: jiahansoft </ p>
  11. * @ Author wanghw
  12. * @ Version 1.0
  13. * /
  14. public class UpLoadAction extends Action {
  15. public ActionForward execute (ActionMapping mapping,
  16. ActionForm form,
  17. HttpServletRequest request,
  18. HttpServletResponse response)
  19. throws Exception {
  20. if (form instanceof UpLoadForm) {/ / If the form is UpLoadsForm
  21. String encoding = request.getCharacterEncoding ();
  22. if ((encoding! = null) & & (encoding.equalsIgnoreCase ("utf-8")))
  23. {
  24. response.setContentType ("text / html; charset = gb2312");
  25. }
  26. UpLoadForm theForm = (UpLoadForm) form;
  27. FormFile file = theForm.getTheFile ();// get the uploaded file
  28. String contentType = file.getContentType ();
  29. String size = (file.getFileSize () + "bytes ");// file size
  30. String fileName = file.getFileName ();// file name
  31. try {
  32. InputStream stream = file.getInputStream ();// read the file
  33. String filePath = request.getRealPath ("/");// get the current system path
  34. ByteArrayOutputStream baos = new ByteArrayOutputStream ();
  35. OutputStream bos = new FileOutputStream (filePath + "/" +
  36. file.getFileName ());
  37. / / Create an output stream uploaded files will upload the file into the web application's root directory.
  38. / / System.out.println (filePath +"/"+ file.getFileName ());
  39. int bytesRead = 0;
  40. byte [] buffer = new byte [8192];
  41. while ((bytesRead = stream.read (buffer, 0, 8192))! = -1) {
  42. bos.write (buffer, 0, bytesRead); / / write a file to the server
  43. }
  44. bos.close ();
  45. stream.close ();
  46. } Catch (Exception e) {
  47. System.err.print (e);
  48. }
  49. / / Request.setAttribute ("dat", file.getFileName ());
  50. request.setAttribute ("contentType", contentType);
  51. request.setAttribute ("size", size);
  52. request.setAttribute ("fileName", fileName);
  53. return mapping.findForward ("display");
  54. }
  55. return null;
  56. }
  57. }

package org.apache.struts.webapp.upload; 
import java.io.*; 
import javax.servlet.http.*; 
import org.apache.struts.action.*; 
import org.apache.struts.upload.FormFile;  

/** 
 * <p>Title:UpLoadAction</p> 
 * <p>Description: QRRSMMS </p> 
 * <p>Copyright: Copyright (c) 2004 jiahansoft</p> 
 * <p>Company: jiahansoft</p> 
 * @author wanghw 
 * @version 1.0 
 */ 

public class UpLoadAction extends Action { 
  public ActionForward execute(ActionMapping mapping, 
                               ActionForm form, 
                               HttpServletRequest request, 
                               HttpServletResponse response) 
      throws Exception { 
       if (form instanceof UpLoadForm) {//  If the form is  UpLoadsForm 
           String encoding = request.getCharacterEncoding(); 

       if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) 
        { 
            response.setContentType("text/html; charset=gb2312"); 
        } 
        UpLoadForm theForm = (UpLoadForm ) form; 
        FormFile file = theForm.getTheFile();//  Upload file access   
        String contentType = file.getContentType(); 

        String size = (file.getFileSize() + " bytes");//  File Size   
        String fileName= file.getFileName();//  File Name   
        try { 
          InputStream stream = file.getInputStream();//  Read the file   
          String filePath = request.getRealPath("/");//  Take the current system path   
          ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
          OutputStream bos = new FileOutputStream(filePath + "/" + 
                                                  file.getFileName()); 
              //  The output of a uploaded file stream into the uploaded file  web  Application's root directory  . 
          //System.out.println(filePath+"/"+file.getFileName()); 
          int bytesRead = 0; 
          byte[] buffer = new byte[8192]; 
          while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) { 
            bos.write(buffer, 0, bytesRead);//  Write a file to the server   
          } 
          bos.close(); 
          stream.close(); 
        }catch(Exception e){ 
          System.err.print(e); 
        } 
        //request.setAttribute("dat",file.getFileName()); 
         request.setAttribute("contentType", contentType); 
         request.setAttribute("size", size); 
         request.setAttribute("fileName", fileName); 

        return mapping.findForward("display"); 
    } 
    return null; 
  } 
} 


Page display.jsp successful

Jsp code
  1. <% @ Page contentType = "text / html; charset = GBK"%>
  2. <% @ Page import = "org.apache.struts.action .*,
  3. java.util.Iterator,
  4. org.apache.struts.Globals "%>
  5. <% @ Taglib uri = "/ tags / struts-html" prefix = "html"%>
  6. Upload successful! From the following information:
  7. <p>
  8. <b> The File name: </ b> <% = request.getAttribute ("fileName")%>
  9. </ P>
  10. <p>
  11. <b> The File content type: </ b> <% = request.getAttribute ("contentType")%>
  12. </ P>
  13. <p>
  14. <b> The File size: </ b> <% = request.getAttribute ("size")%>
  15. </ P>
  16. <hr />
  17. <hr />
  18. <html:link module="/upload" page="/upload.do"> continue to upload </ html: link> </ h2>

<%@ page contentType="text/html; charset=GBK" %> 
<%@ page import="org.apache.struts.action.*, 
                 java.util.Iterator, 
                 org.apache.struts.Globals" %> 
<%@ taglib uri="/tags/struts-html" prefix="html" %> 


  Upload successful  !  By the following information  : 
<p> 
<b>The File name:</b> <%= request.getAttribute("fileName") %> 
</p> 
<p> 
<b>The File content type:</b> <%= request.getAttribute("contentType") %> 
</p> 
<p> 
<b>The File size:</b> <%= request.getAttribute("size") %> 
</p> 
<hr /> 
<hr /> 
<html:link module="/upload" page="/upload.do">   Continue to upload  </html:link></h2> 


Sixth, the test from the site and download the whole directory structure TestStruts into tomcat webapps directory, type in the browser:
http://127.0.0.1:8080/TestStruts/upload/upload.do

Original: http://jc-dreaming.javaeye.com/blog/637923
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Several common file upload in jsp and struts Methods

  • Struts2 Spring Hibernate's easy to integrate

    1. Add Spring 2.0 in Libraries Choose the following four jar, and configure the / WEB-INF/lib under Spring2.0 AOP Libraries Spring2.0 Core Libraries Spring2.0 Persistence Core Libraries Spring2.0 WEb Libraries At the same time, the applicationContext ...

  • Hibernate Inteceptor

    The end of the project stage, the client suddenly put forward a very troublesome but normal demand, the system records all changes must be carried out. Formats such as: 2004.1.1 12:30 Ikuya wind orders Sales Order Date 2004.1.2-> 2004.1.3 The firs ...

  • jboss ejb3 Message Driven Bean

    Super Medium ejb hate. . . . . . . . . . . . . . . . . . . ================================================ To configure a Message Driven Bean in a different application server parameters are not the same. Currently only passed the test jboss. Message Dri

  • RoR explained

    ROR is Ruby on Rails. Ruby is a well-known has been very good dynamic language It's dynamic language. Simple and easy. Dynamic languages are interpreted, but the performance may make a discount, but not absolute, because the application is complex, th

  • FLEX: integrating Spring + Hibernate

    Before a friend also wanted to study development of FLEX. Asked me to help him to be a small sample. Spent a weekend time, to integrate a sampleproject. Client: FLEX Server: Spring2.5 + Hibernate3.2 + Hibernate-annotations3.3.1 + MySQL5 FDS: BlazeDS3 IDE:

  • Process migration from tomcat to websphere changes

    Process migration from tomcat to websphere changes Because customers use the web application server software used by different what tomcat5, tomcat6, websphere5.1, websphere6.1, weblogic8, and so on, and the software used inconsistent standards, ibm's

  • myeclipse plugin

    myeclipsePlug-ins? 1.tomcatPlugin(Start tomcat ):http ://www.sysdeo.com/eclipse/tomcatPlugin.html,2.xVersions of eclipse 3 version 2 .1Version doesn't work. 2.Lomboz(Development of jsp program ,jspDynamic prompt, debugging ):http://forge.objectweb.org/pro

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

  • The level Hibernate cache

    Hibernate cache level: (1) a cache is very short and the session life cycle consistent, also known as session-level cache-level cache or transaction-level cache (2) Ways of Supporting level cache: get (); load (); iterator (); only entity object cach ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries