zoukankan      html  css  js  c++  java
  • 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);
        }
      }
    }
  • 相关阅读:
    Git 游离态的一次问题解决
    idea每次新建项目的默认路径
    springboot 整合 freemarker
    Linux 学习网站
    springtask 基本使用和 cron 表达式
    volatile 关键字 和 i++ 原子性
    python 自动补全
    nagios维护之常见问题
    nagios维护之添加监控
    windows下python文件与文件夹操作
  • 原文地址:https://www.cnblogs.com/yongfengnice/p/10650901.html
Copyright © 2011-2022 走看看