Vert.x 檔案上傳Client

sweetmain發表於2017-12-13

1. pom.xml

        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>3.4.2</version>
        </dependency>

        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web-client</artifactId>
            <version>3.4.2</version>
        </dependency>
複製程式碼

2. Client1.java

import com.xiaoniu.db.Runner;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.FileSystem;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;

import java.net.URLEncoder;
import java.util.UUID;

/**
 * 檔案上傳 Java 客戶端
 */
public class Client1 extends AbstractVerticle {

  // Convenience method so you can run it in your IDE
  public static void main(String[] args) {
    Runner.runExample(Client1.class);
  }

  @Override
  public void start() throws Exception {

    // 只需要修改下面五個引數即可
    final String path = "C:\\Users\\sweet\\Desktop\\png\\Java圖示 - 副本.png";
    final String fileName = "Java圖示副本.png";
    final String reqURI = "/api/fileUpload?name="+ URLEncoder.encode(fileName, "UTF-8");
    final String host = "127.0.0.1";
    final Integer port = 7777;
    // -------------------------

    FileSystem fs = vertx.fileSystem();
    String uuid = UUID.randomUUID().toString();
    WebClient webClient = WebClient.create(vertx, new WebClientOptions().setMaxPoolSize(2));
    Buffer buffer = Buffer.buffer();
    buffer.appendString("--"+uuid+"\n");
    String h = "Content-Disposition: form-data; name=\"file\"; filename=\""+fileName+"\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n";
    buffer.appendString(h);

    Future<Buffer> future = Future.future();
    fs.readFile(path, future);

    future.setHandler(buffer1 -> {
      if (buffer1.succeeded()) {
        buffer.appendBuffer(buffer1.result());
        buffer.appendString("\r\n--"+ uuid +"--\r\n");

        HttpRequest<Buffer> req = webClient.post(port, host, reqURI);
        req.putHeader("Content-Length", "" + buffer.length());
        req.putHeader("Content-Type", "multipart/form-data; boundary="+uuid);

        req.sendBuffer(buffer, resp -> {
          if (resp.succeeded()) {
            System.out.println("resp : " + System.currentTimeMillis());
            JsonObject jsonObject = resp.result().bodyAsJsonObject();
            System.out.println(jsonObject.encodePrettily());
          } else {
            resp.cause().printStackTrace();
          }
        });
      } else {
        buffer1.cause().printStackTrace();
      }
    });
  }
}
複製程式碼

3. Run Main方法

4. Runner.java

https://github.com/vert-x3/vertx-examples/blob/master/core-examples/src/main/java/io/vertx/example/util/Runner.java

相關文章