尝试从文件加载文件体 - Android

时间:2016-10-26 02:19:07

标签: java android file io

我尝试从Android上的最终用户选择上传文件 用户选择是文件,我将其上传到Web服务。我的代码有一个示例 我不明白的是,如果我从画廊中选择一张图片就没问题了。但如果我从存储中选择一个文件,我会得到一个例外:

  

java.io.FileNotFoundException:

/content:/com.android.externalstorage.documents/document/ .... open failed:ENOENT(没有这样的文件或目录)

你能帮我吗?

case PICK_FILE:
    if (resultCode == RESULT_OK) {
        // Get the Uri of the selected file
        Uri uri = intent.getData();
        try {
            // Get the path
            String path = FileGetPath(getApplicationContext(), uri);
            if(path==null){
                File f = new File(uri.toString());
                path = f.getAbsolutePath();
            }
            File file = new File(path);
            HttpPost post = new HttpPost(DomainToCall() + _uploadHandler);

            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.addPart("picture", new FileBody(file));
            post.setEntity(entityBuilder.build());
            HttpResponse response = client.execute(post);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity);
        } catch (Exception e) {

        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为问题不在图像与文件中 问题是关于选择路径

以下代码可以帮助您

Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};

Cursor cursor = getContentResolver().query(
        selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();

File f = new File(filePath);

使用f来传递你的多部分 我没有尝试过它的文件我只是尝试它只为图像 请尝试使用它并告诉我它是否有效