文件上传

文件上传

在此示例中,我们将看到如何上传文件。我们将使用 MultipartBody.Builder 上传 test.ext 文件:

@Test
public void whenUploadFile_thenCorrect() throws IOException {
    RequestBody requestBody = new MultipartBody.Builder()
      .setType(MultipartBody.FORM)
      .addFormDataPart("file", "file.txt",
        RequestBody.create(MediaType.parse("application/octet-stream"),
          new File("src/test/resources/test.txt")))
      .build();

    Request request = new Request.Builder()
      .url(BASE_URL + "/users/upload")
      .post(requestBody)
      .build();

    Call call = client.newCall(request);
    Response response = call.execute();

    assertThat(response.code(), equalTo(200));
}

文件上传进度

@Test
public void whenGetUploadFileProgress_thenCorrect()
  throws IOException {
    RequestBody requestBody = new MultipartBody.Builder()
      .setType(MultipartBody.FORM)
      .addFormDataPart("file", "file.txt",
        RequestBody.create(MediaType.parse("application/octet-stream"),
          new File("src/test/resources/test.txt")))
      .build();

    ProgressRequestWrapper.ProgressListener listener
      = (bytesWritten, contentLength) -> {
        float percentage = 100f * bytesWritten / contentLength;
        assertFalse(Float.compare(percentage, 100) > 0);
    };

    ProgressRequestWrapper countingBody
      = new ProgressRequestWrapper(requestBody, listener);

    Request request = new Request.Builder()
      .url(BASE_URL + "/users/upload")
      .post(countingBody)
      .build();

    Call call = client.newCall(request);
    Response response = call.execute();

    assertThat(response.code(), equalTo(200));
}

ProgressListener 接口定义如下:

public interface ProgressListener {
  void onRequestProgress(long bytesWritten, long contentLength);
}

ProgressRequestWrapper 接口定义如下:

public class ProgressRequestWrapper extends RequestBody {

  @Override
  public void writeTo(BufferedSink sink) throws IOException {
    BufferedSink bufferedSink;

    countingSink = new CountingSink(sink);
    bufferedSink = Okio.buffer(countingSink);

    delegate.writeTo(bufferedSink);

    bufferedSink.flush();
  }
}
protected class CountingSink extends ForwardingSink {
  private long bytesWritten = 0;

  public CountingSink(Sink delegate) {
    super(delegate);
  }

  @Override
  public void write(Buffer source, long byteCount) throws IOException {
    super.write(source, byteCount);

    bytesWritten += byteCount;
    listener.onRequestProgress(bytesWritten, contentLength());
  }
}
上一页