android - 如何使用文件获取图像目录
问题描述
我正在向服务器发送图像,我使用了 okhttp3 multipart,但发送后显示 ENOENT(没有这样的文件或目录)
这是结果:-
java.io.FileNotFoundException:内容:/storage/emulated/0/DCIM/Camera/JPEG_20190813_161656_-733797711.jpg:打开失败:ENOENT(没有这样的文件或目录)
okhttp3.RequestBody body = new okhttp3.MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("user_id", String.valueOf(SharedPref.getInt1(getApplicationContext(), PropnexConstant.SYSID)))
// .addFormDataPart("message", "hi")
.addFormDataPart("file", "test",
okhttp3.RequestBody.create(MediaType.parse("image/jpg"), new File(cameraFilePath)))
.build();
Log.d("OKHTTP3_FILES", "Requested Body");
Log.d("OKHTTP3_FILES", "Requested Body " + body);
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.header("Authorization", "Bearer " + prefs.getData(Constants.CHATTOKEN))
.post(body)
.build();
私有字符串cameraFilePath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
//This is the directory in which the file will be created. This is the default location of Camera photos
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Camera");
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for using again
cameraFilePath = "content://" + image.getAbsolutePath();
return image;
}
解决方案
你可以试试下面的代码: -
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName="JPEG_"+stamp+".jpg";
File photo = new File(Environment.getExternalStorageDirectory(), imageFileName);
return photo;
}
注意:- 目前 getExternalStoragePublicDirectory() 已弃用,请改用 getExternalFilesDir()。
推荐阅读
- python - 使用 estimator api 避免 tf.data.Dataset.from_tensor_slices
- python - 减少使用 numpy 的一行代码的内存使用量
- python - Jupyter笔记本中python 3中标识符中的无效字符,箭头指向负号。我的清单中不能有否定词吗?
- javascript - 字母猜谜游戏,最终猜测后剩余的猜测不返回“0”?
- sql-server-2014 - 使用 LEAD 函数过滤到连续值的一个实例的连续行的日期差异
- javascript - React State 数据无法作为道具传递
- string - Pandas:打印“匹配”而不是仅打印布尔结果
- lambda - Kotlin 中奇怪的 lambda
- xml - XSLT 属性字符串测试
- dart - 使用 dart 或/和 AngularDart 实现质量和完整的 PWA(渐进式 Web 应用程序)