从 Base64 创建文件会导致“PathNotFoundException”

问题描述 投票:0回答:1

基本上我正在尝试在虚拟服务器上使用socket.io 在设备之间发送文件。

因此,我在 Android 设备上将文件转换为 Base64 格式,并使用 socket.io 将其发送到 ios 模拟器。

然后我创建一个临时文件以将接收到的字节写入其中。

我为我的应用程序创建了一个自定义文件夹结构,并将 tempFile 复制到该文件夹中。

一切正常,我可以看到文件夹中的文件,但我的应用程序显示此错误:

“解析图像编解码器时抛出以下 PathNotFoundException: 无法检索文件长度,路径='/storage/emulated/0/AppName/SubFolder1/SubFolder2/Subfolder3/20240504-104447-128-164.jpg'(操作系统错误:没有这样的文件或目录,errno = 2)“

这个路径“路径:/storage/emulated/0/AppName/SubFolder1/SubFolder2/SubFolder3/20240504-104447-128-164.jpg”

函数“createFileFromBase64”应该从自定义文件夹结构中创建的文件返回文件路径,以将其作为字符串保存到对象中,但返回的路径似乎是错误的,我不明白问题是什么。

Future<String> createFileFromBase64({Object? objectVar,String? username}) async {
      final filename = NowFilename.gen(ext: '.jpg');
      Uint8List bytes = convertBase64ToByte(base64File: objectVar?.message);
      File createdTempFile =await createTempFile(bytes: bytes);
      String fileAdresse = "";
    try{
       final Directory? platformDirectory = await getPlatformDirectory();
       final Directory? modiPlatformDirectory = Platform.isIOS?platformDirectory:await modifyAndroidDirectory(directory: platformDirectory);
        final Directory appDocDirFolder =  Directory('${modiPlatformDirectory?.path}/SubFolder1/$username/subFolder1');
        if (!await appDocDirFolder.exists()) {
          await appDocDirFolder.create(recursive: true);
          final File newImage = await createdTempFile.copy('${appDocDirFolder.path}/$filename');
          await newImage.create();
          fileAdresse = newImage.path;
        }else{
          final File newImage = await createdTempFile.copy('${appDocDirFolder.path}/$filename');
          await newImage.create();
           fileAdresse = newImage.path;
        }

    
    }catch(e){
      print(e);
    } 
    return fileAdresse;
    }


 Future<String> getTempDir()async{
    Directory tempDir = await getTemporaryDirectory();
    return tempDir.path;
  }

  Uint8List convertBase64ToByte({String? base64File}){
    return base64.decode(base64File!);
  }

  Future<File> createTempFile({List<int>? bytes})async{
    File finalTempFile=File("");
    try{
        String path = await getTempDir();
        File tempFile = File("$path/tempFile");
        File createdTempFile = await tempFile.writeAsBytes(bytes!);
        finalTempFile = createdTempFile;
    }catch(e){
      print(e);
    }
    return finalTempFile;
  } 

谢谢,如果您需要更多信息,请告诉我!

flutter file socket.io
1个回答
0
投票

我怀疑

newImage.create()
是问题所在 - 我认为如果你复制一个文件,它就会被创建,然后当你调用它时,它会用一个完全空的文件覆盖它。尝试删除这些行,看看是否可以解决问题。

如果这不起作用,我会尝试简化一下。我不认为临时文件步骤是必要的 - 您应该能够直接写入应用程序目录,这将消除另一个错误源。或者,您可以尝试看看是否能够显示临时文件。

如果这些都不起作用,则数据很可能在传输过程中已损坏。值得比较两侧的 base64(您可能可以使用

hashCode
属性来执行此操作,而不是查看整个字符串)以确保它们相同。您可以尝试将图像数据保存到内存中并直接在小部件中显示,而不是写入文件系统。

如果仍然无法正常工作,您可以尝试将所有代码放在一台设备上 - 对图像进行编码然后解码,并确保代码正确,并且图像甚至可以在原始设备上显示。

© www.soinside.com 2019 - 2024. All rights reserved.