gpt4 book ai didi

android - 从存储中选择文件后获取文件路径

转载 作者:行者123 更新时间:2023-11-29 02:30:04 25 4
gpt4 key购买 nike

我正在尝试制作上传图片(后来还有视频)android 应用程序。所以我想从存储中获取文件图像,然后在 imageView 中显示,然后在按下按钮内它将上传到服务器。

我偶然发现图像路径不存在的问题,不知道为什么。这是我的代码:从设备获取图像的按钮:

buttonUploadPhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media
.EXTERNAL_CONTENT_URI);
i.setType("image/*");
startActivityForResult(i, REQUEST_IMAGE);
}
});

我的 Activity 结果代码:

super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

String filename = imageUri.getPath();
destination = new File(Environment.getExternalStorageDirectory(), filename + ".jpg");
imagePath = destination.getAbsolutePath();
Log.e(LOG, "imagePath: " + imagePath);

setcardPic.setImageBitmap(selectedImage);
buttonSubmitPhoto.setVisibility(View.VISIBLE);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}

}else {
Toast.makeText(getApplicationContext(), "You haven't picked Image",Toast.LENGTH_LONG).show();
}

我从那里得到了图像路径,但它不是正确的名称,它给我这样的:/storage/emulated/0/external/images/media/298.jpg,实际文件名就像 cherry.jpg

这里是我的上传按钮代码:

public int uploadFile(String sourceFileUri) {

String fileName = sourceFileUri;
Log.e(LOG, "fileName :" + fileName);
showUploadButton = false; //revert upload button to hidden
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
File sourceFile = new File(sourceFileUri);
Log.e(LOG, "running upload file :" + fileName);

if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e(LOG, "Source File not exist :" + imagePath);
return 0;
} else { ... (upload to server this part is working)

最佳答案

试试这个

final Uri imageUri = data.getData();
String path = getRealPathFromURI(getApplicationContext(), imageUri);

函数在哪里

public 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();
}
}
}

希望对您有所帮助。这将为您返回文件的原始路径。

关于android - 从存储中选择文件后获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49993850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com