首页 > 解决方案 > 如何使用文件获取图像目录

问题描述

我正在向服务器发送图像,我使用了 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;
}

标签: androidokhttp3

解决方案


你可以试试下面的代码: -

 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()。


推荐阅读