android使用OkHttp或者上传图片显示进度

public class UploadImageBody extends RequestBody {

  private File mFile;
  private String mContentType;
  private ProgressListener mListener;

  @Override
  public MediaType contentType() {
    return MediaType.parse(mContentType);
  }

  @Override
  public void writeTo(BufferedSink sink) throws IOException {
    Source source = null;
    try {
      source = Okio.source(mFile);
      long total = 0;
      long read;

      while ((read = source.read(sink.buffer(), 8192)) != -1) {
        total += read;
        sink.flush();
        if (mListener != null) {
          mListener.onProgress(total, mFile.length());
        }
      }
    } finally {
      Util.closeQuietly(source);
    }
  }

  @Override
  public long contentLength() {
    return mFile.length();
  }

  public interface ProgressListener {

    void onProgress(long current, long total);
  }


  public static final class Builder {

    private String mFilePath;
    private ProgressListener mListener;

    public Builder withFilePath(String filePath) {
      this.mFilePath = filePath;
      return this;
    }

    public Builder withListener(ProgressListener mListener) {
      this.mListener = mListener;
      return this;
    }

    private String getFileName() {
      return FileUtil.getFileName(mFilePath);
    }

    public MultipartBody.Part buildPart() {
      UploadImageBody uploadImageBody = new UploadImageBody();
      uploadImageBody.mListener = this.mListener;
      uploadImageBody.mContentType = "application/octet-stream";
      uploadImageBody.mFile = new File(mFilePath);
      return MultipartBody.Part.createFormData("file", getFileName(), uploadImageBody);
    }
  }
}

 

posted @ 2019-04-03 19:08  yongfengnice  阅读(763)  评论(0编辑  收藏  举报