閱讀完了相關資料,並測試以後,我把過程列出來:
- 安裝 Commons 中的 FileUpload 以及 IO 套件。我下載的是 commons-fileupload-1.1.tar.gz 和 commons-io-1.2.tar.gz。
- 將兩個 tar.gz 檔解壓縮之後,將 commons-fileupload-1.1.jar 和 commons-io-1.2.jar 放置於 tomcat/common/lib 內。我用的 Tomcat 版本是 5.5.x。
- 重新啟動 tomcat。
- 產生一個可以由 nobody 寫入的目錄,該目錄最好不要在 web server 能夠存取的路徑上。例如,產生一個 /usr/local/fileupload 的目錄。
- 產生一個檔案上傳的網頁如下:
- 你可以依照你的需求來修改下列程式,本程式是參考 Using FileUpload:
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import org.apache.commons.fileupload.servlet.*; import org.apache.commons.fileupload.disk.*; import org.apache.commons.fileupload.*; import java.util.*; public class fileuploaddemo extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // setup output message PrintWriter output; res.setContentType("text/html;charset=Big5"); output = res.getWriter(); StringBuffer buf = new StringBuffer(); buf.append("
\n"); buf.append("File Upload Test"); buf.append(" \n"); buf.append("File Upload Test
\n"); // first check if the upload request coming in is a multipart request boolean isMultipart = ServletFileUpload.isMultipartContent(req); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { // parse this request by the handler // this gives us a list of items from the request items = upload.parseRequest(req); } catch(FileUploadException e) { } Iterator itr = items.iterator(); while(itr.hasNext()) { FileItem item = (FileItem) itr.next(); // check if the current item is a form field or an uploaded file if(!item.isFormField()) { // get the name of the field String fieldName = item.getFieldName(); if(fieldName.equals("myfile")) { // the item must be an uploaded file save it to disk. String name = item.getName(); System.out.println("Upload Filename: " + name); File savedFile = new File("/usr/local/uploads/" + name); try { item.write(savedFile); } catch (Exception e) { System.out.println("cannot save the uploaded file."); } } } } buf.append("\n"); output.println(buf.toString()); output.close(); } }
沒有留言:
張貼留言