当前位置: 代码迷 >> JavaScript >> 常见的几种jsp和struts中文件下传方法总结
  详细解决方案

常见的几种jsp和struts中文件下传方法总结

热度:522   发布时间:2012-09-08 10:48:07.0
常见的几种jsp和struts中文件上传方法总结

使用FileUpload组件上传文件

文件上传在web应用中非常普遍,要在jsp环境中实现文件上传功能是非常容易的,因为网上有许多用java开发的文件上传组件,本文以commons-fileupload组件为例,为jsp应用添加文件上传功能。
common-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/下载。用该组件可实现一次上传一个或多个文件,并可限制文件大小。
下载后解压zip包,将commons-fileupload-1.0.jar复制到tomcat的webapps\你的webapp\WEB-INF\lib\下,目录不存在请自建目录。
新建一个servlet: Upload.java用于文件上传:


Java代码 复制代码
  1. public?class?Upload?extends?HttpServlet?{ ??
  2. ??
  3. ????private?String?uploadPath?=?"C:\\upload\\";?//?上传文件的目录 ??
  4. ????private?String?tempPath?=?"C:\\upload\\tmp\\";?//?临时文件目录 ??
  5. ??
  6. ????public?void?doPost(HttpServletRequest?request, ??
  7. ????HttpServletResponse?response) ??
  8. ????throws?IOException,?ServletException ??
  9. ????{ ??
  10. ????} ??
  11. } ??
  12. 在doPost()方法中,当servlet收到浏览器发出的Post请求后,实现文件上传。以下是示例代码: ??
  13. public?void?doPost(HttpServletRequest?request, ??
  14. HttpServletResponse?response) ??
  15. throws?IOException,?ServletException ??
  16. { ??
  17. ????try?{ ??
  18. ????????DiskFileUpload?fu?=?new?DiskFileUpload(); ??
  19. ????????//?设置最大文件尺寸,这里是4MB ??
  20. ????????fu.setSizeMax(4194304); ??
  21. ????????//?设置缓冲区大小,这里是4kb ??
  22. ????????fu.setSizeThreshold(4096); ??
  23. ????????//?设置临时目录: ??
  24. ????????fu.setRepositoryPath(tempPath); ??
  25. ??
  26. ????????//?得到所有的文件: ??
  27. ????????List?fileItems?=?fu.parseRequest(request); ??
  28. ????????Iterator?i?=?fileItems.iterator(); ??
  29. ????????//?依次处理每一个文件: ??
  30. ????????while(i.hasNext())?{ ??
  31. ????????????FileItem?fi?=?(FileItem)i.next(); ??
  32. ????????????//?获得文件名,这个文件名包括路径: ??
  33. ????????????String?fileName?=?fi.getName(); ??
  34. ????????????//?在这里可以记录用户和文件信息 ??
  35. ????????????//?... ??
  36. ????????????//?写入文件,暂定文件名为a.txt,可以从fileName中提取文件名: ??
  37. ????????????fi.write(new?File(uploadPath?+?"a.txt")); ??
  38. ????????} ??
  39. ????} ??
  40. ????catch(Exception?e)?{ ??
  41. ????????//?可以跳转出错页面 ??
  42. ????} ??
  43. } ??
  44. 如果要在配置文件中读取指定的上传文件夹,可以在init()方法中执行: ??
  45. public?void?init()?throws?ServletException?{ ??
  46. ????uploadPath?=?.... ??
  47. ????tempPath?=?.... ??
  48. ????//?文件夹不存在就自动创建: ??
  49. ????if(!new?File(uploadPath).isDirectory()) ??
  50. ????????new?File(uploadPath).mkdirs(); ??
  51. ????if(!new?File(tempPath).isDirectory()) ??
  52. ????????new?File(tempPath).mkdirs(); ??
  53. }??
public class Upload extends HttpServlet {

    private String uploadPath = "C:\\upload\\"; // 上传文件的目录
    private String tempPath = "C:\\upload\\tmp\\"; // 临时文件目录

    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException
    {
    }
}
在doPost()方法中,当servlet收到浏览器发出的Post请求后,实现文件上传。以下是示例代码:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
    try {
        DiskFileUpload fu = new DiskFileUpload();
        // 设置最大文件尺寸,这里是4MB
        fu.setSizeMax(4194304);
        // 设置缓冲区大小,这里是4kb
        fu.setSizeThreshold(4096);
        // 设置临时目录:
        fu.setRepositoryPath(tempPath);

        // 得到所有的文件:
        List fileItems = fu.parseRequest(request);
        Iterator i = fileItems.iterator();
        // 依次处理每一个文件:
        while(i.hasNext()) {
            FileItem fi = (FileItem)i.next();
            // 获得文件名,这个文件名包括路径:
            String fileName = fi.getName();
            // 在这里可以记录用户和文件信息
            // ...
            // 写入文件,暂定文件名为a.txt,可以从fileName中提取文件名:
            fi.write(new File(uploadPath + "a.txt"));
        }
    }
    catch(Exception e) {
        // 可以跳转出错页面
    }
}
如果要在配置文件中读取指定的上传文件夹,可以在init()方法中执行:
public void init() throws ServletException {
    uploadPath = ....
    tempPath = ....
    // 文件夹不存在就自动创建:
    if(!new File(uploadPath).isDirectory())
        new File(uploadPath).mkdirs();
    if(!new File(tempPath).isDirectory())
        new File(tempPath).mkdirs();
}






编译该servlet,注意要指定classpath,确保包含commons-upload-1.0.jar和tomcat\common\lib\servlet-api.jar。
配置servlet,用记事本打开tomcat\webapps\你的webapp\WEB-INF\web.xml,没有的话新建一个。
典型配置如下:

Web.xml代码 复制代码
  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. ??
  6. <web-app> ??
  7. ????<servlet> ??
  8. ????????<servlet-name>Upload</servlet-name> ??
  9. ????????<servlet-class>Upload</servlet-class> ??
  10. ????</servlet> ??
  11. ??
  12. ????<servlet-mapping> ??
  13. ????????<servlet-name>Upload</servlet-name> ??
  14. ????????<url-pattern>/fileupload</url-pattern> ??
  15. ????</servlet-mapping> ??
  16. </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>




配置好servlet后,启动tomcat,写一个简单的html测试:

Struts代码 复制代码
  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>

注意action="fileupload"其中fileupload是配置servlet时指定的url-pattern。

二:
选择上传文件页面:selfile.jsp,如此访问此页面:

Jsp代码 复制代码
  1. <html:link?module="/upload"?page="/upload.do">?继续上传</html:link></h2>? ??
  2. ??
  3. --------------------------------------------? ??
  4. <%@?page?contentType="text/html;?charset=GBK"?%>? ??
  5. <%@?page?import="org.apache.struts.action.*,? ??
  6. ?????????????????java.util.Iterator,? ??
  7. ?????????????????org.apache.struts.Globals"?%>? ??
  8. <%@?taglib?uri="/tags/struts-bean"?prefix="bean"?%>? ??
  9. <%@?taglib?uri="/tags/struts-html"?prefix="html"?%>? ??
  10. <%@?taglib?uri="/tags/struts-logic"?prefix="logic"?%>? ??
  11. <logic:messagesPresent>? ??
  12. ???<ul>? ??
  13. ???<html:messages?id="error">? ??
  14. ??????<li><bean:write?name="error"/></li>? ??
  15. ???</html:messages>? ??
  16. ???</ul><hr?/>? ??
  17. </logic:messagesPresent>? ??
  18. <html:html>? ??
  19. ??
  20. <html:form?action="uploadsAction.do"?enctype="multipart/form-data">? ??
  21. <html:file?property="theFile"/>? ??
  22. <html:submit/>? ??
  23. </html:form>? ??
  24. </html:html>???
<html:link module="/upload" page="/upload.do"> 继续上传</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 id="error"> 
      <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> 



表单bean:? UpLoadForm.java

Java代码 复制代码
  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. /**? ?
  7. ?*?<p>Title:UpLoadForm</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. ??
  15. public?class?UpLoadForm?extends?ActionForm?{? ??
  16. ??public?static?final?String?ERROR_PROPERTY_MAX_LENGTH_EXCEEDED?=?"org.apache.struts.webapp.upload.MaxLengthExceeded";? ??
  17. ??protected?FormFile?theFile;? ??
  18. ??public?FormFile?getTheFile()?{? ??
  19. ??????return?theFile;? ??
  20. ??}? ??
  21. ??public?void?setTheFile(FormFile?theFile)?{? ??
  22. ??????this.theFile?=?theFile;? ??
  23. ??}? ??
  24. ???public?ActionErrors?validate(? ??
  25. ????????ActionMapping?mapping,? ??
  26. ????????HttpServletRequest?request)?{? ??
  27. ????????????? ??
  28. ????????ActionErrors?errors?=?null;? ??
  29. ????????//has?the?maximum?length?been?exceeded?? ??
  30. ????????Boolean?maxLengthExceeded?=? ??
  31. ????????????(Boolean)?request.getAttribute(? ??
  32. ????????????????MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);? ??
  33. ????????????????? ??
  34. ????????if?((maxLengthExceeded?!=?null)?&&?(maxLengthExceeded.booleanValue()))?{? ??
  35. ????????????errors?=?new?ActionErrors();? ??
  36. ????????????errors.add(? ??
  37. ????????????????ActionMessages.GLOBAL_MESSAGE?,? ??
  38. ????????????????new?ActionMessage("maxLengthExceeded"));? ??
  39. ????????????errors.add(? ??
  40. ????????????????ActionMessages.GLOBAL_MESSAGE?,? ??
  41. ????????????????new?ActionMessage("maxLengthExplanation"));? ??
  42. ????????}? ??
  43. ????????return?errors;? ??
  44. ??
  45. ????}? ??
  46. ??
  47. }???
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; 

    } 

} 




处理上传的文件:UpLoadAction.java?

Java代码 复制代码
  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. /**? ?
  8. ?*?<p>Title:UpLoadAction</p>? ?
  9. ?*?<p>Description:?QRRSMMS?</p>? ?
  10. ?*?<p>Copyright:?Copyright?(c)?2004?jiahansoft</p>? ?
  11. ?*?<p>Company:?jiahansoft</p>? ?
  12. ?*?@author?wanghw? ?
  13. ?*?@version?1.0? ?
  14. ?*/? ??
  15. ??
  16. public?class?UpLoadAction?extends?Action?{? ??
  17. ??public?ActionForward?execute(ActionMapping?mapping,? ??
  18. ???????????????????????????????ActionForm?form,? ??
  19. ???????????????????????????????HttpServletRequest?request,? ??
  20. ???????????????????????????????HttpServletResponse?response)? ??
  21. ??????throws?Exception?{? ??
  22. ???????if?(form?instanceof?UpLoadForm)?{//如果form是UpLoadsForm? ??
  23. ???????????String?encoding?=?request.getCharacterEncoding();? ??
  24. ??
  25. ???????if?((encoding?!=?null)?&&?(encoding.equalsIgnoreCase("utf-8")))? ??
  26. ????????{? ??
  27. ????????????response.setContentType("text/html;?charset=gb2312");? ??
  28. ????????}? ??
  29. ????????UpLoadForm?theForm?=?(UpLoadForm?)?form;? ??
  30. ????????FormFile?file?=?theForm.getTheFile();//取得上传的文件? ??
  31. ????????String?contentType?=?file.getContentType();? ??
  32. ??
  33. ????????String?size?=?(file.getFileSize()?+?"?bytes");//文件大小? ??
  34. ????????String?fileName=?file.getFileName();//文件名? ??
  35. ????????try?{? ??
  36. ??????????InputStream?stream?=?file.getInputStream();//把文件读入? ??
  37. ??????????String?filePath?=?request.getRealPath("/");//取当前系统路径? ??
  38. ??????????ByteArrayOutputStream?baos?=?new?ByteArrayOutputStream();? ??
  39. ??????????OutputStream?bos?=?new?FileOutputStream(filePath?+?"/"?+? ??
  40. ??????????????????????????????????????????????????file.getFileName());? ??
  41. ??????????????//建立一个上传文件的输出流,将上传文件存入web应用的根目录。? ??
  42. ??????????//System.out.println(filePath+"/"+file.getFileName());? ??
  43. ??????????int?bytesRead?=?0;? ??
  44. ??????????byte[]?buffer?=?new?byte[8192];? ??
  45. ??????????while?(?(bytesRead?=?stream.read(buffer,?0,?8192))?!=?-1)?{? ??
  46. ????????????bos.write(buffer,?0,?bytesRead);//将文件写入服务器? ??
  47. ??????????}? ??
  48. ??????????bos.close();? ??
  49. ??????????stream.close();? ??
  50. ????????}catch(Exception?e){? ??
  51. ??????????System.err.print(e);? ??
  52. ????????}? ??
  53. ????????//request.setAttribute("dat",file.getFileName());? ??
  54. ?????????request.setAttribute("contentType",?contentType);? ??
  55. ?????????request.setAttribute("size",?size);? ??
  56. ?????????request.setAttribute("fileName",?fileName);? ??
  57. ??
  58. ????????return?mapping.findForward("display");? ??
  59. ????}? ??
  60. ????return?null;? ??
  61. ??}? ??
  62. }???
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) {//如果form是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();//取得上传的文件 
        String contentType = file.getContentType(); 

        String size = (file.getFileSize() + " bytes");//文件大小 
        String fileName= file.getFileName();//文件名 
        try { 
          InputStream stream = file.getInputStream();//把文件读入 
          String filePath = request.getRealPath("/");//取当前系统路径 
          ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
          OutputStream bos = new FileOutputStream(filePath + "/" + 
                                                  file.getFileName()); 
              //建立一个上传文件的输出流,将上传文件存入web应用的根目录。 
          //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);//将文件写入服务器 
          } 
          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; 
  } 
} 



成功页display.jsp?

Jsp代码 复制代码
  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. ??
  7. ??
  8. 上传成功!上传信息如下:? ??
  9. <p>? ??
  10. <b>The?File?name:</b>?<%=?request.getAttribute("fileName")?%>? ??
  11. </p>? ??
  12. <p>? ??
  13. <b>The?File?content?type:</b>?<%=?request.getAttribute("contentType")?%>? ??
  14. </p>? ??
  15. <p>? ??
  16. <b>The?File?size:</b>?<%=?request.getAttribute("size")?%>? ??
  17. </p>? ??
  18. <hr?/>? ??
  19. <hr?/>? ??
  20. <html:link?module="/upload"?page="/upload.do">?继续上传</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" %> 


上传成功!上传信息如下: 
<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"> 继续上传</html:link></h2> 


六、测试
从本站下载整个目录结构TestStruts并放入tomcat的webapps目录下,在浏览器中输入:
http://127.0.0.1:8080/TestStruts/upload/upload.do

原文:http://jc-dreaming.iteye.com/blog/637923

  相关解决方案