如何在jsp中的java程序中获取和使用其上传文件的内容?

时间:2011-09-07 11:53:31

标签: java-ee

我写了一个HTML代码来上传jsp.now中的文件我必须使用这个数据并使用jsp.can中的java程序来处理它你请给我一个如何实现这个的示例代码。

谢谢

1 个答案:

答案 0 :(得分:0)

我注意到你的代码。请按照以下步骤进行操作

  1. 下载apache commons-fileupload和apache commons-io的二进制发行版(FileUpload依赖于Commons IO,因此请确保在继续之前在类路径中的依赖项页面上提到了该版本。)

  2. 提取这两个发行版并在WEB-INF / lib文件夹下复制commons-fileupload-1.2.2.jarcommons-io-2.0.1.jar

  3. 在Servlet中,您需要导入javax.servletjavax.servlet.httpimport java.iojava.util,org.apache.commons.fileuploadorg.apache.commons.fileupload.servletorg.apache.commons.fileupload.disk packages

  4. 演示:

    在WEB-INF / classes文件夹下创建一个servlet文件

    package com.me;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.*;
    import java.io.IOException;
    import java.io.File;
    import java.util.List;
    import java.util.Iterator;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    
    
    public class FileUploadServlet extends HttpServlet
    {
      public void doPost(HttpServletRequest request,
                         HttpServletResponse response) 
                             throws ServletException, IOException
       {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            java.io.PrintWriter pw=response.getWriter();
            final String SUCCESS="/success.jsp";
            final String FAIL="/fail.jsp";
            if(isMultipart) 
             {
              try
               {
    
                 FileItemFactory factory = new DiskFileItemFactory();
                 ServletFileUpload upload = new ServletFileUpload(factory);
                 List items = upload.parseRequest(request);
                 pw.print("total : " + items.size());
                 Iterator iter = items.iterator();
                 while (iter.hasNext()) 
                 {
                    FileItem item = (FileItem) iter.next();
                 pw.print("total : " + item);
                    if(!item.isFormField()) 
                      {
                         String fileName = item.getName();
                         String destFilePath=getServletContext().getRealPath("/upload/" + fileName);
                         File uploadedFile = new File(destFilePath);
                         item.write(uploadedFile);
                       }
                  }
                 request.setAttribute("message","file has been uploaded successfully!");
               }catch(Exception ex)
               {
    
                  ex.printStackTrace();
                  request.setAttribute("message","Cannot upload : " + ex.getMessage());
                  getServletContext().getRequestDispatcher(FAIL).forward(request,response);
               }
               getServletContext().getRequestDispatcher(SUCCESS).forward(request,response);
            }
       }
    }
    

    在WEB-INF / web.xml中配置/注册servlet

    <web-app>
     <servlet>
        <servlet-name>fileupload</servlet-name>
        <servlet-class>com.me.FileUploadServlet</servlet-class>
     </servlet>
     <servlet-mapping>
        <servlet-name>fileupload</servlet-name>
        <url-pattern>/fileupload</url-pattern>
     </servlet-mapping>
    </web-app>
    

    视图内容(upload.jsp)。

    注意:使用“multipart / form-data”

    设置enctype属性
    <form method="post" enctype="multipart/form-data" action="fileupload">
      <input type="file" name="file"/>
      <input type="submit"/>
    </form>
    

    success.jsp和fail.jsp的内容

    ${message}
    

    upload的根目录下创建名为context的文件夹。

    JSP版本(这不是推荐的方式)

    upload1.jsp

    <form method="post" enctype="multipart/form-data" 
    
    action="showfile.jsp">
      <input type="file" name="file"/>
      <input type="submit"/>
    </form>
    

    showfile.jsp

    <%@ page import="java.io.*" %>
    <%@ page import="java.util.List" %>
    <%@ page import="java.util.Iterator" %>
    <%@ page import="org.apache.commons.fileupload.FileItemFactory" %>
    <%@ page import="org.apache.commons.fileupload.FileItem" %>
    <%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
    <%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
    
    
    <%
    
     boolean isMultipart = ServletFileUpload.isMultipartContent(request);
     String content="";
    
     if(isMultipart) 
         {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
    
            Iterator iter = items.iterator();
            while (iter.hasNext()) 
             {
                FileItem item = (FileItem) iter.next();
                if(!item.isFormField()) 
                  {
                     BufferedInputStream buff=new BufferedInputStream(item.getInputStream());
                     byte []bytes=new byte[buff.available()];
                     buff.read(bytes,0,bytes.length);
                     content=new String(bytes);
                  }
              }
         }
    %>
    
    Content of File:
    <pre>
     <%=content%>
    </pre>