【问题标题】:picking file for async-http file upload (uri to file path)为 async-http 文件上传选择文件(uri 到文件路径)
【发布时间】:2017-01-24 21:01:59
【问题描述】:

我知道我的问题已被多次解决,但我找不到任何可以帮助我解决具体问题的方法。

我打算从系统的任何地方选择一个文件:

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }


}

我在这里接受了这个意图:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    switch (requestCode) {
        case FILE_SELECT_CODE:

            if (resultCode == RESULT_OK) {
                // Get the Uri of the selected file
                Uri uri = data.getData();

}

我有这样的上传方法:

private void upload(File file){
    RequestParams params = new RequestParams();
    try {
        params.put("fileToUpload", file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    AsyncHttpClient client = new AsyncHttpClient();
    client.post("http://...", params, new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            System.out.println("statusCode "+statusCode);//statusCode 200
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    });
}

问题是我不知道如何将 onActivity 和 upload 这两个方法“结合”起来,因为我不知道如何处理从 Intent 中获得的信息,以便 AsyncHttpClient 可以使用它。

我尝试将 Uri 转换为绝对路径,但无法管理(似乎适用于图像的在线解决方案)。我也无法将 uri “转换”为文件。

有什么办法可以做到吗?我错过了什么吗?

【问题讨论】:

    标签: java android android-intent android-async-http


    【解决方案1】:

    理想的解决方案是使用ContentResolver 和openInputStream() 在Uri 标识的内容上获取InputStream,然后将该InputStream 传递给您的HTTP 客户端API 以用于上传。

    如果您的 HTTP 客户端 API 不支持使用 InputStream 或可以从其中派生的其他内容(例如,Reader),因此您需要 File,请使用 InputStream 和 @ 987654330@ 在您控制的某个文件上制作内容的本地副本(例如,在getCacheDir() 中)。然后,使用本地副本进行文件上传操作,完成后删除本地副本。

    【讨论】:

    • 是的,谢谢,Async-Http 允许输入流而不是文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    相关资源
    最近更新 更多