您好我正在尝试获取我选择的pdf的真实文件路径,以便我可以将其上传到服务器。
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PDF_REQUEST_CODE) {getApplicationContext();
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
auxFile = new File(uri.getPath());
pdfPath = auxFile.getAbsolutePath();
Toast.makeText(getApplicationContext(),pdfPath,Toast.LENGTH_SHORT)
.show();
} else {
// failed to select file
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
答案 0 :(得分:0)
我想获得真实的文件
没有“真实档案”。您没有显示您用于获得此结果的内容,但可能是ACTION_GET_CONTENT
。那,或ACTION_OPEN_DOCUMENT
,不仅限于您可以访问的文件系统上的文件。他们可以返回Uri
指向内容提供商想要的任何内容:加密内容,无法访问位置的文件,BLOB
列,需要下载的内容等等上。用户选择内容而不是您,用户可以选择任何这些类型的来源。
以便我可以将其上传到服务器
查找一些支持从Uri
上传的HTTP API。
或者,使用ContentResolver
和openInputStream()
获取内容的InputStream
,然后找到一些支持从InputStream
上传的HTTP API。
或者,使用ContentResolver
和openInputStream()
获取内容的InputStream
,将该内容的副本复制到某个临时文件中(例如,在getCacheDir()
中),从临时文件上传,然后在下载完成后删除临时文件。
答案 1 :(得分:0)
试试这个:
fun getPath(uri: Uri): String? {
val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri);
val split = docId.split(":");
val type = split[0];
if ("primary".equals(type, true)) {
return Environment.getExternalStorageDirectory().path + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
val id = DocumentsContract.getDocumentId(uri);
val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else
if (isMediaDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri);
val split = docId.split(":");
val type = split[0];
var contentUri: Uri? = null;
if ("image" == type) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video" == type) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio" == type) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
val selection = "_id=?";
val selectionArgs = arrayOf(split[1])
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equals(uri.getScheme(), true)) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equals(uri.getScheme(), true)) {
return uri.getPath();
}
return null;
}
fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
var cursor: Cursor? = null;
val column = "_data";
val projection = arrayOf(column);
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
val index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
fun isExternalStorageDocument(uri: Uri): Boolean {
return "com.android.externalstorage.documents" == uri.authority;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
fun isDownloadsDocument(uri: Uri): Boolean {
return "com.android.providers.downloads.documents" == uri.authority;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
fun isMediaDocument(uri: Uri): Boolean {
return "com.android.providers.media.documents" == uri.authority;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
fun isGooglePhotosUri(uri: Uri): Boolean {
return "com.google.android.apps.photos.content" == uri.authority;
}
答案 2 :(得分:0)
将那个pdf文件复制到缓存目录后我解决了 请在此处检查完整的解决方案:
public static final String DOCUMENTS_DIR = "documents";
if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
if (id != null && id.startsWith("raw:")) {
return id.substring(4);
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
try {
String path = getDataColumn(context, contentUri, null, null);
if (path != null) {
return path;
}
} catch (Exception e) {}
}
// path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
String fileName = getFileName(context, uri);
File cacheDir = getDocumentCacheDir(context);
File file = generateFileName(fileName, cacheDir);
String destinationPath = null;
if (file != null) {
destinationPath = file.getAbsolutePath();
saveFileFromUri(context, uri, destinationPath);
}
return destinationPath;
}
public static String getFileName(@NonNull Context context, Uri uri) {
String mimeType = context.getContentResolver().getType(uri);
String filename = null;
if (mimeType == null && context != null) {
String path = getPath(context, uri);
if (path == null) {
filename = getName(uri.toString());
} else {
File file = new File(path);
filename = file.getName();
}
} else {
Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
if (returnCursor != null) {
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
filename = returnCursor.getString(nameIndex);
returnCursor.close();
}
}
return filename;
}
public static String getName(String filename) {
if (filename == null) {
return null;
}
int index = filename.lastIndexOf('/');
return filename.substring(index + 1);
}
public static File getDocumentCacheDir(@NonNull Context context) {
File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
// logDir(context.getCacheDir());
// logDir(dir);
return dir;
}
@Nullable
public static File generateFileName(@Nullable String name, File directory) {
if (name == null) {
return null;
}
File file = new File(directory, name);
if (file.exists()) {
String fileName = name;
String extension = "";
int dotIndex = name.lastIndexOf('.');
if (dotIndex > 0) {
fileName = name.substring(0, dotIndex);
extension = name.substring(dotIndex);
}
int index = 0;
while (file.exists()) {
index++;
name = fileName + '(' + index + ')' + extension;
file = new File(directory, name);
}
}
try {
if (!file.createNewFile()) {
return null;
}
} catch (IOException e) {
//Log.w(TAG, e);
return null;
}
//logDir(directory);
return file;
}
private static void saveFileFromUri(Context context, Uri uri, String destinationPath) {
InputStream is = null;
BufferedOutputStream bos = null;
try {
is = context.getContentResolver().openInputStream(uri);
bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
byte[] buf = new byte[1024];
is.read(buf);
do {
bos.write(buf);
} while (is.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) is.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
感谢对此thread
的帮助答案 3 :(得分:-2)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_IMAGE_REQUEST_CODE) {getApplicationContext();
if (resultCode == Activity.RESULT_OK) {
if(data == null){
//no data present
return;
}
Uri selectedFileUri = data.getData();
fPath= FilePath.getPath(this,selectedFileUri);
Log.i(TAG, "Selected File Path:" + fPath);
if(fPath!= null && !fPath.equals("")){
tv.setText(fPath);
}else{
Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
}
tv.setText(fPath);
} else {
// failed to select file
Toast.makeText(getApplicationContext(),
"Sorry! Failed to select file", Toast.LENGTH_SHORT)
.show();
}
}
}