如何从图库图像中检索要用于上传到服务器的文件路径和文件名?

时间:2018-07-27 10:08:02

标签: android filepath android-sdcard android-gallery

我一直在尝试通过从图库中选择图像来获取图像的实际路径和名称,从而在Uri中提供uri uri = data.getData();

我试图从这里检索其文件路径。 我尝试过的东西。 1。

# -*- coding: utf-8 -*-
import logging

import scrapy
from scrapy.shell import inspect_response


class SuvlistingsSpider(scrapy.Spider):
    name = 'SuvListings'
    allowed_domains = ['https://www.gumtree.com.au']
    start_urls = [
        'https://www.gumtree.com.au/s-cars-vans-utes/sydney/carbodytype-suv/forsaleby-ownr/c18320l3003435/',
    ]

    def parse(self, response):
        self.log('Received response for listings page', level=logging.INFO)

        main = response.css('.panel-body.panel-body--flat-panel-shadow.user-ad-collection__list-wrapper')[-1]
        for a in main.css('a'):
            req = response.follow(a, callback=self.parse_item)
            yield req

    def parse_item(self, response):
        0/0
        yield {
            'price': response.xpath('normalize-space(//div[@id="ad-price"]/div/span[1])').extract(),
        }

提供

File file = new File(uri.GetPath);

不是实际路径,而是类似这样的东西。

/sdcard/Download/google-adsense-cheque.jpg

我应该如何检索以上路径及其名称。 我一直在使用图库意图打开并选择图像。

content://com.android.providers.media.documents/document/image%3A37

也使用了这种方法,但是列索引提供了空值。

也在“活动”中对结果进行了尝试。

 public String getImagePath(Uri uri) {
    String selectedImagePath;
    // 1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        selectedImagePath = cursor.getString(column_index);
    } else {
        selectedImagePath = null;
    }

    if (selectedImagePath == null) {
        // 2:OI FILE Manager --- call method: uri.getPath()
        selectedImagePath = uri.getPath();
    }
    return selectedImagePath;
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(projection[0]);
    String filePath = cursor.getString(columnIndex);
    cursor.close();
    Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
    return cursor.getString(column_index);
}

这些是我看过的链接,但没有找到路径。

Get filename and path from URI from mediastore

这是我使用的画廊意图

 @SuppressLint("NewApi")
public static String getFilePath(Context context, Uri uri) throws URISyntaxException {
String selection = null;
String[] selectionArgs = null;
// Uri is different in versions after KITKAT (Android 4.4), we need to
if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
    if (isExternalStorageDocument(uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        return Environment.getExternalStorageDirectory() + "/" + split[1];
    } else if (isDownloadsDocument(uri)) {
        final String id = DocumentsContract.getDocumentId(uri);
        uri = ContentUris.withAppendedId(
                Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
    } else if (isMediaDocument(uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];
        if ("image".equals(type)) {
            uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if ("video".equals(type)) {
            uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if ("audio".equals(type)) {
            uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }
        selection = "_id=?";
        selectionArgs = new String[]{
                split[1]
        };
    }
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
    String[] projection = {
            MediaStore.Images.Media.DATA
    };
    Cursor cursor = null;
    try {
        cursor = context.getContentResolver()
                .query(uri, projection, selection, selectionArgs, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        if (cursor.moveToFirst()) {
            return cursor.getString(column_index);
        }
    } catch (Exception e) {
    }
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
    return uri.getPath();
}
return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}

任何人都可以使用此文件路径和文件名(即“ check.jpeg” ...)将其发送到服务器中吗?

Intent intent = new Intent();
                intent.setType("image/*");
 intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Picture"), RESULT_LOAD_IMAGE);

0 个答案:

没有答案