14/08/2018, 10:53

Upload File trong JSP

Một JSP có thể được sử dụng với một thẻ HTML form để cho phép người dùng upload các file tới Server. Một file được tải lên có thể là file dạng text, nhị phân hoặc hình ảnh hoặc bất kỳ tài liệu nào khác. Tạo một File Upload Form trong JSP HTML code sau tạo một Upload Form. Sau đây là những ...

Một JSP có thể được sử dụng với một thẻ HTML form để cho phép người dùng upload các file tới Server. Một file được tải lên có thể là file dạng text, nhị phân hoặc hình ảnh hoặc bất kỳ tài liệu nào khác.

Tạo một File Upload Form trong JSP

HTML code sau tạo một Upload Form. Sau đây là những điểm quan trọng cần ghi nhớ:

 
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

Nó sẽ hiển thị kết quả sau, cho phép bạn chọn một file từ PC nội bộ và khi người dùng click tại "Upload File", thì Form sẽ được đệ trình cùng với file đã chọn:

 
File Upload: 

Select a file to upload:



Ghi chú: Form trên chỉ là một form giả và sẽ không làm việc, sẽ nên thử code trên tại thiết bị của bạn để làm cho nó làm việc.

Viết Backend JSP Script

Đầu tiên, chúng ta định nghĩa một vị trí để lưu giữ các file được upload. Bạn có thể mã hóa điều này trong chương trình của bạn hoặc tên thư mục này cũng có thể được thêm vào bởi sử dụng một cấu hình ngoại vi chẳng hạn như một phần tử context-param trong web.xml như sau:

 
<web-app>
....
<context-param> 
    <description>Location to store uploaded file</description> 
    <param-name>file-upload</param-name> 
    <param-value>
         c:apache-tomcat-5.5.29webappsdata
     </param-value> 
</context-param>
....
</web-app>

Sau đây là source code cho UploadFile.jsp, mà có thể xử lý nhiều thao tác tải file lên tại cùng một thời điểm. Trước khi tiến hành, bạn chắc chắn rằng:

<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %><%
   File file ;
   int maxFileSize = 5000 * 1024;
   int maxMemSize = 5000 * 1024;
   ServletContext context = pageContext.getServletContext();
   String filePath = context.getInitParameter("file-upload");   // Verify the content type
   String contentType = request.getContentType();
   if ((contentType.indexOf("multipart/form-data") >= 0)) {      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:	emp"));      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );
      try{ 
         // Parse the request to get file items.
         List fileItems = upload.parseRequest(request);         // Process the uploaded file items
         Iterator i = fileItems.iterator();         out.println("<html>");
         out.println("<head>");
         out.println("<title>JSP File upload</title>");  
         out.println("</head>");
         out.println("<body>");
         while ( i.hasNext () ) 
         {
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () )	
            {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("") >= 0 ){
            file = new File( filePath + 
            fileName.substring( fileName.lastIndexOf(""))) ;
            }else{
            file = new File( filePath + 
            fileName.substring(fileName.lastIndexOf("")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded Filename: " + filePath + 
            fileName + "<br>");
            }
         }
         out.println("</body>");
         out.println("</html>");
      }catch(Exception ex) {
         System.out.println(ex);
      }
   }else{
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      out.println("<p>No file uploaded</p>"); 
      out.println("</body>");
      out.println("</html>");
   }
%>

Bây giờ, bạn thử upload file bởi sử dụng HTML form bạn đã tạo ở trên. Khi bạn thử http://localhost:8080/UploadFile.htm, nó sẽ cho kết quả sau:

 
File Upload: 

Select a file to upload:


Nếu JSP script làm việc tốt, file của bạn sẽ được tải lên trong thư mục c:apache-tomcat-5.5.29webappsdata.

0