【问题标题】:Rename a file/Image in flutter在颤动中重命名文件/图像
【发布时间】:2020-05-10 18:36:07
【问题描述】:

我正在使用 image_picker: ^0.6.2+3 包从图库中挑选图片/拍照。

File picture = await ImagePicker.pickImage(
  maxWidth: 800,
  imageQuality: 10,
  source: source, // source can be either ImageSource.camera or ImageSource.gallery
  maxHeight: 800,
);

我得到 picture.path 作为

/Users/[一些路径]/tmp/image_picker_A0EBD0C1-EF3B-417F-9F8A-5DFBA889118C-18492-00001AD95CF914D3.jpg

现在我想将图片重命名为 case01wd03id01.jpg

注意:我不想将它移动到新文件夹

如何重命名它?我在官方文档中找不到。

【问题讨论】:

标签: android ios flutter dart imagepicker


【解决方案1】:

先导入路径包。

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

然后创建一个新的目标路径来重命名文件。

File picture = await ImagePicker.pickImage(
        maxWidth: 800,
        imageQuality: 10,
        source: ImageSource.camera,
        maxHeight: 800,
);
print('Original path: ${picture.path}');
String dir = path.dirname(picture.path);
String newPath = path.join(dir, 'case01wd03id01.jpg');
print('NewPath: ${newPath}');
picture.renameSync(newPath);

【讨论】:

    【解决方案2】:

    Manish Raj's answer 对我不起作用,因为image_picker: ^0.6.7,他们最近在获取返回 PickedFile 而不是 File 的图像或视频时更改了他们的 API。

    我使用的新方法是将PickedFile 转换为File,然后将其复制到应用程序目录中并使用新名称。此方法需要path_provider.dart

    import 'package:path_provider/path_provider.dart';
    
    ...
    ...
    
    PickedFile pickedFile = await _picker.getImage(source: ImageSource.camera);
    
    // Save and Rename file to App directory
    String dir = (await getApplicationDocumentsDirectory()).path;
    String newPath = path.join(dir, 'case01wd03id01.jpg');
    File f = await File(pickedF.path).copy(newPath);
    

    我知道问题表明他们不想将其移动到新文件夹,但这是我能找到的使重命名工作的最佳方法。

    【讨论】:

      【解决方案3】:

      使用此功能仅重命名文件名而不更改文件路径。你可以在有或没有 image_picker 的情况下使用这个函数。

      import 'dart:io';
      
      Future<File> changeFileNameOnly(File file, String newFileName) {
        var path = file.path;
        var lastSeparator = path.lastIndexOf(Platform.pathSeparator);
        var newPath = path.substring(0, lastSeparator + 1) + newFileName;
        return file.rename(newPath);
      }
      

      在您的 dart sdk 上的 file.dart 中阅读更多文档。 希望能帮到你,关注

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-01
        • 2012-11-11
        • 2018-12-20
        • 1970-01-01
        • 1970-01-01
        • 2022-11-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多