我正在尝试制作上传图片(后来还有视频)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);
}
});
我的活动结果代码:
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)