使用OKHTTP3实现Android上传文件百分比进度条

4

有没有人知道如何添加一个进度条,以告诉我上传的文件有多少已上传。以下是我的代码,我已成功从手机中选择文件并将其发送,但问题在于如果我正在上传一个巨大的文件,我会一直等待不知道什么时候才能完成,这就是为什么我需要一个进度条来显示已传输到服务器上的数量。这是我的代码,我尝试了不同的实现,但都不行。

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);

}

}

2个回答

1
我认为你的整个解决方案需要进行一些更正。使用某些对话框暂停用户是不好的做法,而且如果配置更改,上传进度可能会丢失。新线程现在也过于粗糙。因此,首先建议您将上传过程的代码移动到Service或IntentService中。您可以在通知中显示进度和状态,然后使用对话框或Snackbar等提示用户。其次,没有直接的方法来监视上传进度。通常最好的方法是实现自定义RequestBody,通过监听器通知已上传的字节。请参考Tracking progress of multipart file upload using OKHTTP。然后,您可以使用广播或事件总线来发布进度。

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接