[英]Android Upload file Percentage ProgressBar with OKHTTP3
有誰知道如何添加一個進度條,告訴我已經上傳了多少文件 。 這是我在下面的代碼中設法做的,我已設法從我的手機中選擇一個文件,並設法發送它,但問題是,如果我上傳一個巨大的文件,我一直在等待不知道什么時候會完成,這就是為什么我需要一個進度條,告訴我有多少已轉移到服務器。 這是我已經嘗試過不同實現的代碼,但無濟於事。
public class MainActivity extends AppCompatActivity {
private Button fileUploadBtn;
protected static String IPADDRESS = "http://10.42.0.1/hugefile/save_file.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileUploadBtn = (Button) findViewById(R.id.btnFileUpload);
pickFile();
}
private void pickFile() {
fileUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MaterialFilePicker()
.withActivity(MainActivity.this)
.withRequestCode(10).start();
}
});
}
ProgressDialog progress;
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
progress = new ProgressDialog(MainActivity.this);
progress.setTitle("Uploading File(s)");
progress.setMessage("Please wait...");
progress.show();
if (requestCode == 10 && resultCode == RESULT_OK) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type), f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type", content_type)
.addFormDataPart("uploaded_file", file_path.substring(file_path.lastIndexOf("/") + 1), file_body).build();
Request request = new Request.Builder()
.url(IPADDRESS)
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
Log.d("Server response", response.body().string());
if (!response.isSuccessful()) {
throw new IOException("Error : " + response);
}
progress.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
private String getMimeType(String path) {
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
}
我認為你的整個解決方案需要一些修正。 暫停用戶某些對話框是不好的做法,如果配置更改,您的上傳進度也會丟失。 而新線程我現在真的太粗暴了。 首先,我建議您在Service或IntentService中移動上傳過程的代碼。 您可以在通知中顯示進度和狀態,然后通過對話框或小吃欄等提醒用戶。其次,沒有直接的方法來監控上傳進度。 通常最好的方法是實現自定義RequestBody,它將通知通過監聽器上傳的字節。 請使用OKHTTP跟蹤多部分文件上傳的進度然后您可以使用廣播或事件總線來發布進度。
我設法通過一些改進來解決它,這里是遇到相同問題的人的解決方案的鏈接https://github.com/MakuSimz/Android-Multipart-Upload-with-Progress
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.