Flutter - 无法将文件复制到新路径

Posted

技术标签:

【中文标题】Flutter - 无法将文件复制到新路径【英文标题】:Flutter - Cannot copy file to new path 【发布时间】:2019-03-04 16:54:45 【问题描述】:

我想把图片复制到应用程序目录,但是总是报这个错误:

[ERROR:flutter/shell/common/shell.cc(181)] Dart 错误:未处理 异常:E/flutter(4159):FileSystemException:无法复制文件到 '/data/user/0/com.vendetta.recipe/app_flutter',路径 = '/storage/emulated/0/android/data/com.vendetta.recipe/files/Pictures/a6fd32a9-60b2-4cff-8f10-2ffc2933bf751208556873045090039.jpg' (操作系统错误:是一个目录,errno = 21)E/flutter(4159):#0 _文件.copy。 (dart:io/file_impl.dart:340:9) E/flutter (4159): #1 _RootZone.runUnary (dart:async/zone.dart:1379:54) E/flutter (4159): #2 _FutureListener.handleValue (dart:async/future_impl.dart:129:18) E/flutter (4159): #3 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:642:45) E/flutter (4159): #4 Future._propagateToListeners (dart:async/future_impl.dart:671:32) E/颤振(4159):#5 Future._completeWithValue (dart:async/future_impl.dart:486:5) E/flutter (4159): #6 Future._asyncComplete。 (dart:async/future_impl.dart:516:7) E/flutter (4159): #7 _microtaskLoop (dart:async/schedule_microtask.dart:41:21) E/flutter (4159): #8 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)

我想复制这张图片,以确保当我保存它时,用户不会删除重要文件。我想将这个文件存储在数据库中。

这是我复制图像的代码,是用image_picker拍摄的:

Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path;
File newImage = await _image.copy('$path');

我希望有人能够解决我的问题。

【问题讨论】:

【参考方案1】:

path 是目录/data/user/0/com.vendetta.recipe/app_flutter。尝试向其添加/filename.jpg

File newImage = await _image.copy('$path/filename.jpg');

【讨论】:

嘿,这会在 Android 10 中引发错误,errno 13,权限被拒绝 用户需要授予您写入某些目录的权限 等等,你的意思是我每次都需要询问用户存储访问权限吗?截至目前,我在打开应用程序时请求许可 但我得到了错误,即使我已经请求用户许可。我找到的解决方案是在29编译dk,并在Android manifest.xml中添加“allowLegacyExternalStorage”为true。我了解到这是由于 Android 10 中的范围存储,但是从现在开始如何使用外部存储目录? @NithinSai 你找到解决方案了吗我也面临这个问题【参考方案2】:

请试试这个,然后你的问题就解决了

我提供给你也可以动态复制任何扩展名的文件

按照这些步骤-

1.首先添加这个导入

import 'package:path/path.dart' as path;

2.获取带扩展名的文件名

 var basNameWithExtension = path.basename(sourceFile.path);

3.然后将扩展名传递给

var file =  await moveFile(sourceFile,newPath+"/"+basNameWithExtension);

4.然后写这个方法

Future<File> moveFile(File sourceFile, String newPath) async 
    try 
      /// prefer using rename as it is probably faster
      /// if same directory path
      return await sourceFile.rename(newPath);
     catch (e) 
      /// if rename fails, copy the source file 
      final newFile = await sourceFile.copy(newPath);
      return newFile;
    
  
    然后你会得到预期的结果

【讨论】:

喂,这样删除原文件吗? 我想使用复制或将我的文件移动到一个目录到另一个目录我该怎么做这是我的文件路径'/storage/emulated/0/Android/data/com.wasisoft.topi/ files/video1.mp4' 在这里我想移动我的文件路径'/storage/emulated/0/Download/video1. mp4',

以上是关于Flutter - 无法将文件复制到新路径的主要内容,如果未能解决你的问题,请参考以下文章

怎么把sql数据库从旧电脑移动到新电脑安装?​

将 ImageField 的内容复制到 Django 中的新文件路径

列出所有子目录中的所有 *.jpg 文件并复制到新文件夹

Applescript 将文件复制到新文件夹

将文件复制到新位置

flutter - 如何在Dart/Flutter中将某些元素从一个Map复制到新Map中?