我想从我的 android 应用程序,将图像上载到 Google 驱动器
基于本教程。
调试他们的示例项目的时候我看到典型的 fileUri =
file:///storage/sdcard0/Pictures/IMG_20131117_090231.jpg
我想在我的应用程序上载现有的照片。
像这样检索它的路径
private void GetAnyImage()
{
File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Pictures/Screenshots");
// --> /storage/sdcard0/Pictures/Screenshots
Log.d("File path ", dir.getPath());
String dirPath=dir.getAbsolutePath();
if(dir.exists() && dir.isDirectory()) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
startActivityForResult(intent,REQUEST_ID);
}
}
最终会到达这个典型的 fileUri =content://media/external/images/media/74275
然而当运行这行代码
private void saveFileToDrive() {
// progressDialog = ProgressDialog.show(this, "", "Loading...");
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
// File's binary content
java.io.File fileContent = new java.io.File(fileUri.getPath());
FileContent mediaContent = new FileContent("image/jpeg", fileContent);
// File's metadata.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
File file = service.files().insert(body, mediaContent).execute();
出现错误:
java.io.FileNotFoundException: /external/images/media/74275: open failed: ENOENT (No such file or directory)
如何解决这问题?
如何转换 content://media/external/images/media/Y
到 file:///storage/sdcard0/Pictures/X.jpg
吗?
解决方法 1:
什么会喜欢这项工作对你来说吗?这不会是查询的内容冲突解决程序来存储的文件路径数据寻找该内容的条目
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
这最终会给你你可以构造从一个文件 uri 的绝对文件路径