JavaServlet編程及應用之八
|
| Java關鍵字導航 |
| 網絡 J2ME 手機游戲 JavaCard Struts 游戲 分析器 JAAS EJB JavaMail 設計模式 J2EE |
Java Servlet 在網絡上的編程應用,如利用Servlet 上傳和下載文件、Servlet 的數據庫編程、在Servlet 中發送和接受郵件以及Java Servlet 在RMI和XML等方面的應用,由于篇幅有限,在這里就不在多介紹了,下面再舉一個Servlet 上傳的例子。
在Web 應用程序中,用戶向服務器上傳文件是非常普遍的操作。使用Servlet 實現文件的上傳是比較簡單的。
編程思路:下面的UploadServlet.java ,其主要功能為從InputStream 中讀取文件內容,將上傳文件保存在根目錄下,且文件名與上傳文件的文件名一致。
UploadServlet.java 的源代碼如下:(代碼節選)
| import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class UploadServlet extends HttpServlet { //default maximum allowable file size is 1000k static final int MAX_SIZE = 1024000; //instance variables to store root and success message String rootPath, successMessage; /** * init method is called when servlet is initialized. */ public void init(ServletConfig config) throws ServletException { super.init(config); //get path in which to save file rootPath = config.getInitParameter("RootPath"); if (rootPath == null) { rootPath = "/"; } /*Get message to show when upload is complete. Used only if a success redirect page is not supplied.*/ successMessage = config.getInitParameter("SuccessMessage"); if (successMessage == null) { successMessage = "File upload complete!"; } } /** * doPost reads the uploaded data from the request and writes * it to a file. */ public void doPost(HttpServletRequest request, HttpServletResponse response) { ServletOutputStream out=null; DataInputStream in=null; FileOutputStream fileOut=null; try { /*set content type of response and get handle to output stream in case we are unable to redirect client*/ response.setContentType("text/plain"); out = response.getOutputStream(); //get content type of client request String contentType = request.getContentType(); out.println("contentType= " + contentType); //make sure content type is multipart/form-data if(contentType != null && contentType.indexOf( "multipart/form-data") != -1) { //open input stream from client to capture upload file in = new DataInputStream(request.getInputStream()); //get length of content data int formDataLength = request.getContentLength(); out.println("ContentLength= " + formDataLength); //allocate a byte array to store content data byte dataBytes[] = new byte[formDataLength]; //read file into byte array int bytesRead = 0; int totalBytesRead = 0; int sizeCheck = 0; while (totalBytesRead < formDataLength) { //check for maximum file size violation sizeCheck = totalBytesRead + in.available(); if (sizeCheck > MAX_SIZE) { out.println("Sorry, file is too large to upload."); return; } ........... ........... |