1. Trang chủ
  2. » Thể loại khác

upload file trong servlet

4 108 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 4
Dung lượng 204,36 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Upload File trong Servlet Một Servlet 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.. • Thuộc tính action trong thẻ form nên được thiết lập

Trang 1

Upload File trong Servlet

Một Servlet 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 upload file có thể là một text hoặc image file hoặc bất kỳ tài liệu nào khác

Tạo một File Upload Form

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

Thuộc tính Phương thức của thẻ form nên được thiết lập là phương thức POST và

phương thức GET không thể được sử dụng

Thuộc tính enctype của thẻ form nên được thiết lập là multipart/form-data

Thuộc tính action trong thẻ form nên được thiết lập là một servlet file mà sẽ xử lý việc upload file tại Backend Server Ví dụ sau sử dụng servlet là UploadServlet để

upload file

• Để upload một file đơn, bạn nên sử dụng một thẻ <input /> đơn với thuộc tính là type=”file” Để cho phép upload nhiều file lên, bạn sử dụng nhiều thẻ input với các giá trị thuộc tính khác nhau Trình duyệt liên kết một nút Browse với từng giá trị đó

<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:

NOTE: This is just dummy form and would not work

Trang 2

Viết Backend Servlet:

Servlet sau với tên UploadServlet sẽ chăm sóc file đã được tải lên và lưu giữ nó trong thư

mục <Tomcat-installation-directory>/webapps/data Tên thư mục nà 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.29\webapps\data\ </param-value> </context-param> </web-app>

Dưới đây là source code cho UploadServlet mà có thể xử lý việc upload nhiều file tại cùng một thời điểm Trước khi vào ví dụ, bạn chắc chắn rằng:

• Ví dụ sau phụ thuộc vào FileUpload, vì thế chắc chắn rằng bạn đang sử dụng phiên

bản mới nhất của commons-fileupload.x.x.jar file trong Classpath của bạn Bạn

có thể tải nó về từ: http://commons.apache.org/fileupload/

• FileUpload phụ thuộc vào Commons IO, vì thể đảm bảo rằng bạn có phiên bản mới

nhất của commons-io-x.x.jar file trong Classpath của bạn Bạn có thể download nó

tại: http://commons.apache.org/io/

• Trong khi kiểm nghiệm ví dụ này, bạn nên upload một file mà có kích cỡ nhỏ

hơnmaxFileSize, nếu không thì file đó sẽ không được tải lên

• Bạn chắc chắn đã tạo ra thư mục c:\temp và c:\apache-tomcat-5.5.29\webapps\data

// Import required java libraries import java.io.*; import java.util.*;

import javax.servlet ServletConfig ; import javax.servlet ServletException ;

import javax.servlet.http HttpServlet ; import

javax.servlet.http HttpServletRequest ; import

javax.servlet.http HttpServletResponse ; import

org.apache.commons.fileupload FileItem ; import

org.apache.commons.fileupload FileUploadException ; import

org.apache.commons.fileupload.disk DiskFileItemFactory ; import

org.apache.commons.fileupload.servlet ServletFileUpload ; import

org.apache.commons.io.output.*; public class UploadServlet extends

HttpServlet { private boolean isMultipart; private String

filePath; private int maxFileSize = 50 * 1024 ; private int

maxMemSize = 4 * 1024 ; private File file ; public void init( ){ // Get the file location where it would be stored filePath = getServletContext().getInitParameter( "file-upload" ); } public void

Trang 3

doPost( HttpServletRequest request, HttpServletResponse

response) throws ServletException , java.io IOException {

// Check that we have a file upload request isMultipart = ServletFileUpload isMultipartContent(request);

response.setContentType( "text/html" ); java.io PrintWriter out = response.getWriter( ); if ( !isMultipart ){

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>" ); return ; } 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:\\temp" )); // 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>Servlet 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(); String contentType = fi getContentType(); 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: " + fileName + "<br>" ); } } out println( "</body>" );

out println( "</html>" ); } catch ( Exception ex) {

System out println(ex); } } public void doGet( HttpServletRequest request, HttpServletResponse response)

throws ServletException , java.io IOException { throw new ServletException ( "GET method used with " + getClass( ).getName( )+ ": POST method required." ); } }

Biên dịch và chạy Servlet

Biên dịch UploadServlet trên và tạo các entry cần thiết trong web.xml như sau:

Trang 4

<servlet> <servlet-name>UploadServlet</servlet-name>

<servlet-class>UploadServlet</servlet-class> </servlet> <servlet-mapping>

<servlet-name>UploadServlet</servlet-name>

<url-pattern>/UploadServlet</url-pattern> </servlet-mapping>

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

File Upload:

Select a file to upload:

Nếu mọi thứ là ổn, file của bạn sẽ được upload trong c:\apache-tomcat-5.5.29\webapps\data\ directory

Ngày đăng: 02/12/2017, 22:27

TỪ KHÓA LIÊN QUAN

w