`

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

    博客分类:
  • JSP
阅读更多
使用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用于文件上传:



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,没有的话新建一个。
典型配置如下:
<?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测试:
<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,如此访问此页面:
<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

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 
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 
<%@ 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



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xiedayun/archive/2007/04/09/1558186.aspx
分享到:
评论
2 楼 花神47699 2015-01-20  
[img] [/img]
1 楼 花神47699 2015-01-20  
几节课

相关推荐

Global site tag (gtag.js) - Google Analytics