Android Studio 如何在Android 11和12中获取PDF文件路径

zsbz8rwp  于 2022-12-13  发布在  Android
关注(0)|答案(3)|浏览(643)

我尝试了很多代码获取PDF路径在android 11或12,但只工作在android 10或以下设备.你能帮我吗?我分享我的代码行

如此用心的呼唤

第一个

getPath调用方式如下

public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor == null) return null;
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String s = cursor.getString(column_index);
        cursor.close();
        return s;
    }
vxqlmq5t

vxqlmq5t1#

如果你想访问一个文件或者想从MediaStore返回的URI中获取文件路径,我有一个library,它可以处理你可能遇到的所有异常。这包括磁盘、内部磁盘和可移动磁盘上的所有文件。例如,当从Dropbox中选择一个文件时,该文件将被复制到你有完全访问权限的应用程序目录中,然后将返回复制的文件路径。

piv4azn7

piv4azn72#

让我分享我的经验,以解决这个东西后,所以阅读所有。
从URI获取输入流

final Uri pdfUri= data.getData();
getContentResolver().openInputStream(pdfUri)

然后使用InputStream进行操作,就像我使用okHttp上传PDF一样

try {

RequestBody pdffile = new RequestBody() {
    @Override public MediaType contentType() { return MediaType.parse("application/pdf"); }
    @Override public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        try {
            source = Okio.source(inputStream);
            sink.writeAll(source);
        } finally {
            Util.closeQuietly(source);
        }
    }
    @Override
    public long contentLength() {
        try {
            return inputStream.available();
        } catch (IOException e) {
            return 0;
        }
    }
};

RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
        .addFormDataPart("file", "fname.pdf", pdffile)
        //.addFormDataPart("Documents", value) // uncomment if you want to send Json along with file
        .build();

Request request = new Request.Builder()
        .url(serverURL)
        .post(requestBody)
        .build();

OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS)
        .addInterceptor(chain -> {
            Request original = chain.request();
            Request.Builder builder = original.newBuilder().method(original.method(), original.body());
            builder.header("key", key);
            return chain.proceed(builder.build());
        })
        .build();

client.newCall(request).enqueue(new Callback() {

    @Override
    public void onFailure(final Call call, final IOException e) {
        // Handle the error
        setIsLoading(false);
        getNavigator().uploadIssue("Facing some issue to upload this file.");
    }

    @Override
    public void onResponse(final Call call, final Response response) throws IOException {
        setIsLoading(false);
        if (!response.isSuccessful()) {
            getNavigator().uploadIssue("Facing some issue to upload this file.");

        }else {
            // Upload successful
            getNavigator().uploadedSucessfully();
        }

    }
});

return true;
} catch (Exception ex) {
    // Handle the error
    ex.printStackTrace();
}
gajydyqb

gajydyqb3#

这一个帮助在我的情况下对Android 11希望任何人得到这个有帮助的

private String copyFile(Uri uri, String newDirName) {
    Uri returnUri = uri;

    Cursor returnCursor = this.getContentResolver().query(returnUri, new String[]{
            OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE
    }, null, null, null);

    /*
     * Get the column indexes of the data in the Cursor,
     *     * move to the first row in the Cursor, get the data,
     *     * and display it.
     * */
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
    returnCursor.moveToFirst();
    String name = (returnCursor.getString(nameIndex));
    String size = (Long.toString(returnCursor.getLong(sizeIndex)));

    File output;
    if (!newDirName.equals("")) {
        File dir = new File(this.getFilesDir() + "/" + newDirName);
        if (!dir.exists()) {
            dir.mkdir();
        }
        output = new File(this.getFilesDir() + "/" + newDirName + "/" + name);
    } else {
        output = new File(this.getFilesDir() + "/" + name);
    }
    try {
        InputStream inputStream = this.getContentResolver().openInputStream(uri);
        FileOutputStream outputStream = new FileOutputStream(output);
        int read = 0;
        int bufferSize = 1024;
        final byte[] buffers = new byte[bufferSize];
        while ((read = inputStream.read(buffers)) != -1) {
            outputStream.write(buffers, 0, read);
        }

        inputStream.close();
        outputStream.close();

    } catch (Exception e) {

        Log.e("Exception", e.getMessage());
    }

    return output.getPath();
}

如果R.string.app。

相关问题