【问题标题】:Image File Disappears, Not Uploaded图像文件消失,未上传
【发布时间】:2017-12-11 16:01:30
【问题描述】:

我有一个创建文件的应用程序如下:

File image = File.createTempFile(
                imageFileName,  // prefix
                ".jpg",         // suffix
                storageDir      // directory
        );

执行此调用 image.exists() 返回 true。然后我将文件名作为额外数据发送到相机:

takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,  
                           Uri.fromFile(photoFile));

startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);

我保存如下所示的文件路径:“file:/storage/emulated/0/Pictures/JPEG_20171211_162442_-1697405777.jpg”。当结果从 Camera 活动返回时,我可以使用文件路径创建位图:

bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));

我成功地显示了位图,但是当我使用路径创建文件对象时,File.exists() 返回 false,尽管我可以使用“adb shell ls”查看文件。更重要的是,我无法使用 POST 调用将图像加载到服务器,如下所示:

File sourceFile = new File(sourceImageFile);
        String fileName = sourceFile.getName();
        Log.d(Constants.TAG, "File...::::" + sourceFile + " : " + sourceFile.exists());
        final MediaType MEDIA_TYPE = MediaType.parse("image/jpeg");
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("xxx_upload_file", fileName, RequestBody.create(MEDIA_TYPE, sourceFile))
                .addFormDataPart("content", "upload_img")
                .addFormDataPart("XXX_id", Constants.xxx_ID)
                .addFormDataPart("session_id", mPicActivity.mSessionID)
                .addFormDataPart("source_url", "Chatbot")
                .build();

        Request request = new Request.Builder()
                .url(Constants.CHATBOT_URL_BASE + Constants.STORE_EXAMINE)
                .post(requestBody)
                .build();


        mClient.newCall(request).enqueue(new Callback()...);

服务器响应其他调用,因此不是连接或 URL 问题。上传失败是因为文件突然不存在(即使它确实存在,如上所述)?问题是否与“模拟”文件路径有关。

【问题讨论】:

  • File sourceFile = new File(sourceImageFile);the file path which looks like this: "file:/storage/emulated/0/Pictures/JPEG_20171211_162442_-1697405777.jpg"。那看起来不对。你不是说"file:///storage/..... 吗?文件路径应类似于/storage/emulated/0/Pictures/JPEG_20171211_162442_-1697405777.jpg。因此,从该字符串 sourceImageFile 中删除 file://
  • 我需要截断“file:”协议前缀。 @greenapps,如果您想将此作为答案发布,我会感谢您。

标签: android android-image


【解决方案1】:
"file:/storage/emulated/0/Pictures/JPEG_20171211_162442_-1697405777.jpg". 

应该是这样的

"/storage/emulated/0/Pictures/JPEG_20171211_162442_-1697405777.jpg". 

【讨论】:

    【解决方案2】:

    在保存临时文件时,Android 会在其名称中添加一些随机符号,例如“youfilename.jpgXkd5jrj”。

    检查File image的确切文件名/路径或在文件管理器中查看临时文件目录以查看文件是否真的存在。

    【讨论】:

    • 扩展我写的内容:如果我打开 adb shell,cd 到路径中的目录,然后运行 ​​ls -l 我会看到一个具有正确名称的非零大小的文件。跨度>
    猜你喜欢
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多