我试图创建一个进度对话框来更新更新到服务器的文件数量并在进度对话框中显示它们,我按照这篇文章(https://stackoverflow.com/a/33384551)代码:
public class ProgressRequestBody extends RequestBody {
private File mFile;
private String mPath;
private UploadCallbacks mListener;
private static final int DEFAULT_BUFFER_SIZE = 2048;
public interface UploadCallbacks {
void onProgressUpdate(int percentage);
void onError();
void onFinish();
}
public ProgressRequestBody(final File file, final UploadCallbacks listener) {
mFile = file;
mListener = listener;
}
@Override
public MediaType contentType() {
// i want to upload only images
return MediaType.parse("image/*");
}
@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));
}
}
}
在api界面:
@Multipart
@POST("/upload")
Call<JsonObject> uploadImage(@Part MultipartBody.Part file);
在myActiviy中:
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<JsonObject> request = RetrofitClient.uploadImage(filepart);
request.enqueue(new Callback<JsonObject>{...});
}
@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);
}
}
我遇到的问题是当我尝试传递&#34; fileBody&#34;反对
MultipartBody.Part filePart = MultipartBody.Part.createFormData("image",
file.getName(), fileBody);
我收到错误,因为无法传递文件主体,这是一个错误的论点。
我从这篇文章(https://stackoverflow.com/a/33384551)中获取了参考资料并对其进行了编码,但我得到了错误。
答案 0 :(得分:0)
您缺少档案参数。试试吧
File file = new File(your image path);
ProgressRequestBody fileBody = new ProgressRequestBody(file, this);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", file.getName(), fileBody);