<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Java Servlet 上傳文件 > 原文: [http://zetcode.com/articles/javaservletuploadfile/](http://zetcode.com/articles/javaservletuploadfile/) Java Servlet 上傳文件顯示了如何使用 Servlet 技術在 Java Web 應用中上傳單個文件。 ## Java Servlet Servlet 是 Java 類,可響應特定類型的網絡請求-最常見的是 HTTP 請求。 Java servlet 用于創建 Web 應用。 它們在 servlet 容器(例如 Tomcat 或 Jetty)中運行。 現代 Java Web 開發使用在 servlet 之上構建的框架。 ## HTML 表單編碼類型 POST 請求有三種編碼 HTML 表單方法: * `application/x-www-form-urlencoded` * `multipart/form-data` * `text/plain` `application/x-www-form-urlencoded`是默認編碼。 這些值編碼在由`&`分隔的鍵值元組中。 `=`字符用于鍵和值之間。 非字母數字字符采用百分比編碼。 此編碼類型不適用于二進制文件。 `multipart/form-data`用于非 acsii 數據和二進制文件。 `input`元素的`type`屬性設置為`file`。 `text/plain`用于調試。 ## Java Servlet 上傳文件示例 在以下應用中,我們有一個 Web 表單來選擇要上傳到服務器的文件。 該表單調用 Java servlet,該 servlet 讀取文件并將其保存到目錄中。 ### 上傳目錄 `/var/www`目錄是 Debian Linux 中 Web 內容的標準目錄。 ```java $ ls -ld /var/www/upload/ drwxrwxr-x 2 www-data www-data 4096 Dec 3 14:29 /var/www/upload/ ``` 我們將文件上傳到`/var/www/upload`目錄。 `www-data`組中的用戶可以修改目錄文件。 因此,運行 Web 服務器的用戶必須在此組中。 ### 應用 這是一個 Maven Web 應用。 它部署在 Tomcat 上。 ```java $ tree . ├── nb-configuration.xml ├── pom.xml └── src └── main ├── java │ └── com │ └── zetcode │ └── FileUploadServlet.java └── webapp ├── index.html └── META-INF └── context.xml ``` 這是項目結構。 `pom.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>JavaServletFileUploadEx</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>JavaServletFileUploadEx</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> ``` 這是 Maven POM 文件。 `javax.servlet-api`工件用于 servlet。 `maven-war-plugin`負責收集 Web 應用的所有工件依賴項,類和資源,并將它們打包到 Web 應用存檔(WAR)中。 `context.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <Context path="/JavaServletFileUploadEx"/> ``` 在 Tomcat `context.xml`文件中,我們定義了上下文路徑。 它是 Web 應用的名稱。 `FileUploadServlet.java` ```java package com.zetcode; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @WebServlet(name = "FileUploadServlet", urlPatterns = {"/FileUploadServlet"}, initParams = { @WebInitParam(name = "path", value = "/var/www/upload/") }) @MultipartConfig public class FileUploadServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain;charset=UTF-8"); ServletOutputStream os = response.getOutputStream(); ServletConfig sc = getServletConfig(); String path = sc.getInitParameter("uploadpath"); Part filePart = request.getPart("myfile"); String fileName = filePart.getSubmittedFileName(); InputStream is = filePart.getInputStream(); Files.copy(is, Paths.get(path + fileName), StandardCopyOption.REPLACE_EXISTING); os.print("File successfully uploaded"); } } ``` `FileUploadServlet`將文件上傳到`/var/www/upload`目錄。 ```java @WebServlet(name = "FileUploadServlet", urlPatterns = {"/FileUploadServlet"}, initParams = { @WebInitParam(name = "uploadpath", value = "/var/www/upload/") }) ``` 使用`@WebServlet`批注,我們將 servlet 映射到`/FileUploadServlet` URL 模式,并定義了初始的`uploadpath`變量。 ```java @MultipartConfig ``` servlet 也用`@MultipartConfig`裝飾。 `@MultipartConfig`批注指示 servlet 期望使用`multipart/form-data` MIME 類型進行請求。 ```java @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ``` POST 請求由`doPost()`方法處理。 ```java ServletOutputStream os = response.getOutputStream(); ``` 我們使用`getOutputStream()`方法獲得 servlet 輸出流。 ```java ServletConfig sc = getServletConfig(); String path = sc.getInitParameter("uploadpath"); ``` 我們檢索初始參數。 這是我們要上傳文件的目錄。 ```java Part filePart = request.getPart("myfile"); ``` 使用`getPart()`方法檢索文件部分。 ```java String fileName = filePart.getSubmittedFileName(); InputStream is = filePart.getInputStream(); ``` 我們得到零件的文件名和輸入流。 ```java Files.copy(is, Paths.get(path + fileName), StandardCopyOption.REPLACE_EXISTING); ``` 使用`Files.copy()`,將文件復制到目標目錄。 ```java os.print("File successfully uploaded"); ``` 最后,我們將消息寫回客戶端。 `index.html` ```java <!DOCTYPE html> <html> <head> <title>Uploading a file</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css"> </head> <body> <form class="pure-form pure-form-stacked" method="post" action="FileUploadServlet" enctype="multipart/form-data"> <fieldset> <legend>File:</legend> <input type="file" name="myfile"> <button type="submit" class="pure-button pure-button-primary">Upload</button> </fieldset> </form> </body> </html> ``` 這是選擇要上傳文件的主頁。 它包含一個 HTML 表單。 提交表單后,處理將發送到`FileUploadServlet`。 ```java <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css"> ``` 我們包括 Pure.css 庫,用于創建負責任的頁面。 ```java <form class="pure-form pure-form-stacked" method="post" action="FileUploadServlet" enctype="multipart/form-data"> ``` `method`屬性為 post,因為我們將數據發送到服務器。 `action`屬性指定處理請求的 servlet 的名稱。 `enctype`屬性指定`multipart/form-data`編碼類型,這是使用 HTML 格式上傳文件所必需的。 ```java <input type="file" name="myfile"> ``` `input`標簽的`type`屬性使用戶可以選擇一個文件。 ```java <button type="submit" class="pure-button pure-button-primary">Upload</button> ``` 這是提交按鈕。 在本教程中,我們展示了如何使用 Java Servlet 上傳單個文件。 您可能也對以下相關教程感興趣: [Java Servlet 分頁](/articles/javaservletpagination/), [Java Log4j 教程](/java/log4j/), [Java Servlet RESTful 客戶端](/articles/javaservletrestclient/), [Java `RequestDispatcher`](/java/requestdispatcher/) ,[從 Java servlet](/articles/javaservlettext/) , [Java servlet 圖像教程](/articles/javaservletimage/)或 [Java 教程](/lang/java/)提供純文本
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看