Several common file upload in jsp and struts Methods

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

分类:Java 时间:2010-12-10 人气:224
分享到:
blog comments powered by Disqus

相关文章

  • tomcat web applications deployed in three ways & ant 2011-04-25

    http://wenku.baidu.com/view/a748f87202768e9951e73843.html http://wenku.baidu.com/view/35571b04cc175527072208ac.html

  • The use of Java to achieve Comet style Web applications 2010-03-04

    To explore the development of different implementations of Comet. Jetty and Tomcat look like the popular Java ™ Web server, how to support Comet applications, and learn how to program a different server. Finally, the understanding of the standardizat

  • Using Java to achieve Comet style Web applications 2010-06-29

    Start In this article, I will show you how to use a variety of Java technology to build simple Web applications of the Comet style Program . Readers of the Java Servlet, Ajax, and JavaScript should have some understanding. We will examine some suppor

  • Tomcat Web application using web.xml control Xiangjie (1) 2010-07-30

    Transfer from: http://fanqiang.chinaunix.net/app/web/2006-04-29/4122.shtml Tomcat Web application using web.xml control Xiangjie (1) Study: feng_sundy Source: unknown (2006-04-29 13:39:34) A definition of the head and the root element Deployment desc

  • Optimized web applications using the gzip (filter implementation) 2010-12-25

    2009-05-18 Optimized web applications using the gzip (filter implementation) Previously used filter, which is shielded by the limited access to resources about the path, solve the garbage problem under the Chinese, in fact, the optimized filter web a

  • Tomcat web application deployment 2010-11-06

    Max on us today about web training program in the proper deployment under tomcat. Mainly include: 1.java the classloader in tomcat architecture under http://www.jaxmao.org/tomcat-docs/class-loader-howto.html Wrote Like many server applications, like,

  • Your java code safe? 2010-11-14

    In the development of Java Web applications, you need to ensure that the application has improved security features to add. Speaking of Java security here, we are not talking about the security provided by Java language API, not involving the use of

  • java code conversion process in detail 2011-07-21

    Common JAVA program includes the following categories: * Direct the class to run on the console (including the visual interface of the class) * JSP code class (Note: JSP Servlets class is a variant of) * Servelets class * EJB class * Other classes ca

  • Review Java code, 11 kinds of common errors 2010-09-05

    Bug code review is to eliminate one of the most important ways, these reviews are particularly effective in most of the time. As the code review itself targeted, is overlooking the entire code in the testing process problems and Bug. Also, the code r

  • jsp page using java code 2010-05-28

    Previously, I do not like jsp pages directly to use java code block, mosaic java code, but after work, use this situation, I changed the mind, in fact, it has the convenience of his office ah! <%@ page language="java" import="java.util.*

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 1.162 (s). 12 q(s)