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

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Java 文件上傳 REST 服務 > 原文: [https://javatutorial.net/java-file-upload-rest-service](https://javatutorial.net/java-file-upload-rest-service) 在本教程中,我將解釋如何構建 Java REST Web 服務以通過 HTTP 從任何客戶端上載文件。 將文件上傳到 Web 應用程序是當今的一項常見任務。 許多服務都支持在其網站上上傳圖片或文檔。 使用 Java Web 服務,這很容易實現。 除了 Java Web 容器(由 [Tomcat](http://tomcat.apache.org/),[GlassFish](http://www.oracle.com/us/products/middleware/cloud-app-foundation/glassfish-server/overview/index.html) 或 [JBoss](http://wildfly.org/) 等應用服務器提供)之外,我們還需要 [Jersey](https://github.com/jersey) 使它運行。 首先,我將向您展示如何實現 Web 服務,然后為您提供兩個使用該服務的客戶端示例。 ![Java file upload form](https://img.kancloud.cn/1e/0d/1e0d6e2f821177a3c1ec080f42967809_547x221.jpg) Java 文件上傳表格 ## 構建文件上傳 REST 服務 該文件通過 HTTP POST 以編碼類型`multipart/form-data`從客戶端推送到我們的 Web 服務。 這樣,除了文件之外,您還可以向 POST 請求添加多個參數。 讓我們從需求開始。 您將需要 Web 應用程序服務器(例如 Tomcat,GlassFish 或 JBoss)來部署服務。 另外,我們將使用 jersey 框架來構建我們的服務端點。 請注意,GlassFish 4.x 版本需要 jersey 版本 2 庫,因此如果使用 GlassFish 4,則**請在您的 POM 文件中使用 jersey 2.x 依賴項**。 為了快速參考,您可以在我們的 GitHub 存儲庫中的 [https://github.com/JavaTutorialNetwork/Tutorials/tree/master/FileUploaderRESTService](https://github.com/JavaTutorialNetwork/Tutorials/tree/master/FileUploaderRESTService) 下找到整個項目 我將在此處發布整個 POM 文件,但您需要考慮的是 Jersey 依賴項 ```java <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>net.javatutorial.tutorials</groupId> <artifactId>FileUploaderRESTService</artifactId> <version>1</version> <packaging>war</packaging> <name>File Uploader Rest Service</name> <url>https://javatutorial.net</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-servlet</artifactId> <version>1.17.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-multipart</artifactId> <version>1.8</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <inherited>true</inherited> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <webXml>src/main/webapp/WEB-INF/web.xml</webXml> <webResources> <resource> <!-- this is relative to the pom.xml directory --> <directory>${project.basedir}/src/main/resources </directory> </resource> </webResources> </configuration> </plugin> </plugins> </build> </project> ``` 現在擁有所有必需的庫,讓我們繼續實現 REST 服務。 下面的代碼中有幾個地方我想提醒您注意。 首先請注意`@Consumes(MediaType.MULTIPART_FORM_DATA)`作為請求的編碼類型的用法。 其次,如果愿意,您可能希望向該方法添加其他參數。 例如,您可能要在上傳時傳遞一些描述或其他文本數據。 最后,如果您嘗試將文件上傳到不存在的目錄中,Java 將拋出異常。 為了避免這個問題,我創建了方法`createFolderIfNotExists(StringdirName)`。 ```java package net.javatutorial.tutorials.services; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.sun.jersey.core.header.FormDataContentDisposition; import com.sun.jersey.multipart.FormDataParam; /** * This example shows how to build Java REST web-service to upload files * accepting POST requests with encoding type "multipart/form-data". For more * details please read the full tutorial on * https://javatutorial.net/java-file-upload-rest-service * * @author javatutorial.net */ @Path("/upload") public class FileUploadService { /** The path to the folder where we want to store the uploaded files */ private static final String UPLOAD_FOLDER = "c:/uploadedFiles/"; public FileUploadService() { } @Context private UriInfo context; /** * Returns text response to caller containing uploaded file location * * @return error response in case of missing parameters an internal * exception or success response if file has been stored * successfully */ @POST @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { // check if all form parameters are provided if (uploadedInputStream == null || fileDetail == null) return Response.status(400).entity("Invalid form data").build(); // create our destination folder, if it not exists try { createFolderIfNotExists(UPLOAD_FOLDER); } catch (SecurityException se) { return Response.status(500) .entity("Can not create destination folder on server") .build(); } String uploadedFileLocation = UPLOAD_FOLDER + fileDetail.getFileName(); try { saveToFile(uploadedInputStream, uploadedFileLocation); } catch (IOException e) { return Response.status(500).entity("Can not save file").build(); } return Response.status(200) .entity("File saved to " + uploadedFileLocation).build(); } /** * Utility method to save InputStream data to target location/file * * @param inStream * - InputStream to be saved * @param target * - full path to destination file */ private void saveToFile(InputStream inStream, String target) throws IOException { OutputStream out = null; int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(target)); while ((read = inStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } /** * Creates a folder to desired location if it not already exists * * @param dirName * - full path to the folder * @throws SecurityException * - in case you don't have permission to create the folder */ private void createFolderIfNotExists(String dirName) throws SecurityException { File theDir = new File(dirName); if (!theDir.exists()) { theDir.mkdir(); } } } ``` 最后,我們需要配置`web.xml`以將我們的類注冊為 Web 服務并使其在啟動時運行。 ```java <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>net.javatutorial.tutorials.services</display-name> <servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>net.javatutorial.tutorials.services</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app> ``` 好的! 現在,您可以構建和部署 WAR 文件。 如果您使用上面代碼中提供的完全相同的名稱,則您的服務 URL(假設您在`localhost`上運行)將是:`http://localhost:8080/FileUploaderRESTService-1/rest/upload` ## 文件上傳 HTML 表格 您可以使用非常簡單的 HTML post 表單作為客戶端將文件發送到服務器。 請注意`multipart/form-data`作為編碼類型的用法。 您還需要添加文件類型為`[file]`的輸入 ```java Choose file to upload<br> <form action="http://localhost:8080/FileUploaderRESTService-1/rest/upload" method="post" enctype="multipart/form-data"> <input name="file" id="filename" type="file" /><br><br> <button name="submit" type="submit">Upload</button> </form> ``` 如前所述,您可以向請求中添加其他數據。 在這種情況下,別忘了在網絡服務中處理它?? ## Java 文件上傳客戶端 您可以為 Android 或 Java 中的獨立程序創建文件上傳客戶端。 在下面的示例中,我將使用 Apache http 庫,您將需要以下五個: * commonlog * httpclient * httpclient cache * httpcore * httpmime ```java package net.javatutorial.tutorials.clienst; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.util.EntityUtils; /** * This example shows how to upload files using POST requests * with encoding type "multipart/form-data". * For more details please read the full tutorial * on https://javatutorial.net/java-file-upload-rest-service * @author javatutorial.net */ public class FileUploaderClient { public static void main(String[] args) { // the file we want to upload File inFile = new File("C:\\Users\\admin\\Desktop\\Yana-make-up.jpg"); FileInputStream fis = null; try { fis = new FileInputStream(inFile); DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); // server back-end URL HttpPost httppost = new HttpPost("http://localhost:8080/FileUploaderRESTService-1/rest/upload"); MultipartEntity entity = new MultipartEntity(); // set the file input stream and file name as arguments entity.addPart("file", new InputStreamBody(fis, inFile.getName())); httppost.setEntity(entity); // execute the request HttpResponse response = httpclient.execute(httppost); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println("[" + statusCode + "] " + responseString); } catch (ClientProtocolException e) { System.err.println("Unable to make connection"); e.printStackTrace(); } catch (IOException e) { System.err.println("Unable to read file"); e.printStackTrace(); } finally { try { if (fis != null) fis.close(); } catch (IOException e) {} } } } ``` 您將在我們的 GitHub 存儲庫中找到項目文件 [https://github.com/JavaTutorialNetwork/Tutorials/tree/master/FileUploaderJavaClient](https://github.com/JavaTutorialNetwork/Tutorials/tree/master/FileUploaderJavaClient) 謝謝閱讀。 一如既往歡迎評論??
                  <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>

                              哎呀哎呀视频在线观看