Servlet 可以與 HTML form 標(biāo)簽一起使用允許用戶(hù)將文件上傳到服務(wù)器。上傳的文件可以是文本文件或圖像文件或任何文檔。
下述 HTML 代碼創(chuàng)建了一個(gè)文件上傳表單。以下是需要注意的幾點(diǎn):
表單 method 屬性應(yīng)該設(shè)置為 POST 方法且不能使用 GET 方法。
表單 enctype 屬性應(yīng)該設(shè)置為 multipart/form-data.
表單 action 屬性應(yīng)該設(shè)置為 servlet 文件,能夠在后端服務(wù)器處理文件上傳。下面的例子是使用 UploadServlet servlet 來(lái)上傳文件的。
<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>
這將顯示如下所示的結(jié)果,允許從本地計(jì)算機(jī)中選擇一個(gè)文件,當(dāng)用戶(hù)點(diǎn)擊“上傳文件”時(shí),表單會(huì)和選擇的文件一起提交:
File Upload: Select a file to upload:
NOTE: This is just dummy form and would not work.
以下是 servlet UploadServlet,會(huì)接受上傳的文件并把它儲(chǔ)存在目錄 <Tomcat-installation-directory>/webapps/data
中。使用外部配置,如 web.xml 中的 context-param 元素,這個(gè)目錄名也可以被添加,如下所示:
<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>
以下是 UploadServlet 的源代碼,可以一次處理多個(gè)文件的上傳。在繼續(xù)操作之前,請(qǐng)確認(rèn)下列各項(xiàng):
下述例子依賴(lài)于 FileUpload,所以一定要確保在你的 classpath 中有最新版本的 commons-fileupload.x.x.jar 文件。你可以從 http://commons.apache.org/fileupload/ 中下載。
FileUpload 依賴(lài)于 Commons IO,所以一定要確保在你的 classpath 中有最新版本的 commons-io-x.x.jar 文件??梢詮?http://commons.apache.org/io/ 中下載。
在測(cè)試下面實(shí)例時(shí),你上傳的文件大小不能大于 maxFileSize,否則文件將無(wú)法上傳。
// 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 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.");
}
}
編譯上述 servlet UploadServlet 并在 web.xml 文件中創(chuàng)建所需的條目,如下所示:
<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>
現(xiàn)在嘗試使用上面創(chuàng)建的 HTML 表單來(lái)上傳文件。當(dāng)你訪(fǎng)問(wèn) http://localhost:8080/UploadFile.htm
時(shí),它會(huì)顯示如下所示的結(jié)果,這將有助于你從本地計(jì)算機(jī)中上傳任何文件。
File Upload:Select a file to upload:
如果你的 servelt 腳本能正常工作,那么你的文件會(huì)被上傳到 c:\apache-tomcat-5.5.29\webapps\data\
目錄中。
更多建議: