Android用retrofit上传图片,android – 通过Retrofit 2上传图片时是否可以...

首先,您应该使用等于或高于2.0 beta2的Retrofit 2版本.

二,创建新类扩展RequestBody:

public class ProgressRequestBody extends RequestBody {

private File mFile;

private String mPath;

private UploadCallbacks mListener;

private String content_type;

private static final int DEFAULT_BUFFER_SIZE = 2048;

public interface UploadCallbacks {

void onProgressUpdate(int percentage);

void onError();

void onFinish();

}

Take note, I added content type so it can accommodate other types aside image

public ProgressRequestBody(final File file, String content_type, final UploadCallbacks listener) {

this.content_type = content_type;

mFile = file;

mListener = listener;

}

@Override

public MediaType contentType() {

return MediaType.parse(content_type+"/*");

}

@Override

public long contentLength() throws IOException {

return mFile.length();

}

@Override

public void writeTo(BufferedSink sink) throws IOException {

long fileLength = mFile.length();

byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];

FileInputStream in = new FileInputStream(mFile);

long uploaded = 0;

try {

int read;

Handler handler = new Handler(Looper.getMainLooper());

while ((read = in.read(buffer)) != -1) {

// update progress on UI thread

handler.post(new ProgressUpdater(uploaded, fileLength));

uploaded += read;

sink.write(buffer, 0, read);

}

} finally {

in.close();

}

}

private class ProgressUpdater implements Runnable {

private long mUploaded;

private long mTotal;

public ProgressUpdater(long uploaded, long total) {

mUploaded = uploaded;

mTotal = total;

}

@Override

public void run() {

mListener.onProgressUpdate((int)(100 * mUploaded / mTotal));

}

}

}

Third, create interface

@Multipart

@POST("/upload")

Call uploadImage(@Part MultipartBody.Part file);

/* JsonObject above can be replace with you own model, just want to

make this notable. */

Now you can get progress of your upload.

In your activity (or fragment):

class MyActivity extends AppCompatActivity implements ProgressRequestBody.UploadCallbacks {

ProgressBar progressBar;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

progressBar = findViewById(R.id.progressBar);

ProgressRequestBody fileBody = new ProgressRequestBody(file, this);

MultipartBody.Part filePart =

MultipartBody.Part.createFormData("image", file.getName(), fileBody);

Call request = RetrofitClient.uploadImage(filepart);

request.enqueue(new Callback() {

@Override

public void onResponse(Call call, Response response) {

if(response.isSuccessful()){

/* here we can equally assume the file has been downloaded successfully because for some reasons the onFinish method might not be called, I have tested it myself and it really not consistent, but the onProgressUpdate is efficient and we can use that to update out progress on the UIThread, and we can then set our progress to 100% right here because the file already downloaded finish. */

}

}

@Override

public void onFailure(Call call, Throwable t) {

/* we can also stop our progress update here, although I have not check if the onError is being called when the file could not be downloaded, so I will just use this as a backup plan just incase the onError did not get called. So I can stop the progress right here. */

}

});

}

@Override

public void onProgressUpdate(int percentage) {

// set current progress

progressBar.setProgress(percentage);

}

@Override

public void onError() {

// do something on error

}

@Override

public void onFinish() {

// do something on upload finished

// for example start next uploading at queue

progressBar.setProgress(100);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值