Want to display file list using jsp

前端 未结 2 1971
北恋
北恋 2021-01-16 17:43

I am new to netbeans with glassfish server.My html code looks like,


    
相关标签:
2条回答
  • 2021-01-16 18:11

    To process HTTP multipart/form-data requests in a servlet, use Apache Commons FileUpload. You should end up with the uploaded file in a FileItem. It has a write() method.

    String filename = FilenameUtils.getName(fileItem.getName()); 
    fileItem.write(new File("c:/upload", filename)); // Name must be unique!
    

    For the usage guide and more code examples, just check their User Guide.


    To display a list of files in the folder, you need to use the java.io.File API, it has a listFiles() method which returns a list of all files (paths) in a certain path. Do it in a preprocessing servlet which forwards the request to a JSP to display the list.

    File[] files = new File("c:/upload").listFiles();
    request.setAttribute("files", files);
    request.getRequestDispatcher("/WEB-INF/uploads.jsp").forward(request, response);
    

    In the /WEB-INF/uploads.jsp file use JSTL <c:forEach> to iterate over the File[].

    <c:forEach items="${files}" var="file">
        <c:out value="${file.name}" /> (${file.length / 1024}KB)<br/>
    </c:forEach>
    

    Note that this is of course open for more (UI) finetuning, but that's up to you. I assume that you already know the HTML/JSP/Servlet basics.

    0 讨论(0)
  • 2021-01-16 18:22

    you can do like that

         <%!
          Object path;
          public void getDirectory(String path, Vector files, Vector folder){
          File directory=new File(path); 
         File []file=directory.listFiles();
            for(int i=0; i<file.length; i++){
           if(file[i].isDirectory()){
            folder.add(file[i].getName());
           }
           else{
            files.add(file[i].getName());
           }
        }
     }
     %>
    
    <table>
    <%
    
        path=session.getAttribute("fileName");
       Vector file=new Vector(), folder=new Vector();
      getDirectory("C:/FileFolderProject/WebContent/"+path,file,folder);
       out.println("<music>");
    
      for(int a=0; a<file.size(); a++){
        %>
         <tr>
         <td>
          <img src="images/editfileimg.jpg" alt="file">
          </td>
         <td>
         <% 
         out.println("<file>"+file.elementAt(a).toString()+"</file><br/>");
        %>
         </td>
         <tr>
      <%
    
      }
      out.println("</music>");
      %>
       </table>
    
    0 讨论(0)
提交回复
热议问题