我有以下代码将捕获的图像写入SD卡
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
使用如下:
public void takePicture(){
i= new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //Open camera
file = Uri.fromFile(getOutputMediaFile());
i.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(i, 100);
}
捕获图像后,文件的路径将发送到以下函数:
public void sendForUpload(String uploadUrl, String path){
File dir = Environment.getExternalStorageDirectory();
File imgFile = new File(dir, path);
sendFile(uploadUrl, imgFile);
}
public void sendFile(String uploadUrl, File file){
Log.d(GlobalClass.TAG, "File has arrived here");
Log.d(GlobalClass.TAG, file.toString());
byte[] fileData1 = new byte[(int) file.length()];
FileInputStream fileInputStream;
try{
fileInputStream = new FileInputStream(file);
fileInputStream.read(fileData1);
fileInputStream.close();
}catch (Exception e){
Log.d("Error", e.getMessage());
}
.... // Upload
}
此处try
阻止失败,日志显示错误:
D/Error: /storage/emulated/0/storage/emulated/0/Pictures/AppName/IMG_20160516_120506.jpg: open failed: ENOENT (No such file or directory)
如何将文件读入sendFile()
?
答案 0 :(得分:2)
仔细查看错误中的路径:
/storage/emulated/0/storage/emulated/0/Pictures/AppName/IMG_20160516_120506.jpg
您会注意到/storage/emulated/0
重复。
替换:
File dir = Environment.getExternalStorageDirectory();
File imgFile = new File(dir, path);
使用:
File imgFile = new File(path);
答案 1 :(得分:0)
我有这个问题的解决方案。这个问题很容易解决。
只需转到您的 AndroidManifest.xml
然后=>应用
只需输入这一行 => android:requestLegacyExternalStorage="true"
您的问题将得到解决。