我正在尝试从我的Android应用上传图片到Google云端硬盘,
基于此tutorial。
当我调试他们的示例项目时,我看到一个典型的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
?
答案 0 :(得分:67)
这样的事情对你有用吗?这样做是查询内容解析器以查找为该内容条目存储的文件路径数据
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答案 1 :(得分:5)
如果您只想要位图,这也可以
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();
示例uri:content:// media / external / images / media / 12345