簡體   English   中英

重命名 Flutter 中的文件或圖像

[英]Rename a file or image in Flutter

我正在使用 image_picker 從圖庫中挑選圖像/拍照:^0.6.2+3 package。

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

注意:我不想將其移動到新文件夾

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

首先導入路徑包。

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);

Manish Raj 的回答對我image_picker: ^0.6.7 ,因為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);

我知道問題表明他們不想將其移動到新文件夾,但這是我能找到的使重命名工作的最佳方法。

使用此功能僅重命名文件名而不更改文件路徑。 您可以在有或沒有 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 中閱讀更多文檔。 希望能幫到你,關注

導入路徑包

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

下面的代碼

 final file =File("filepath here"); //your file path
 String dir = path.dirname(file.path); //get directory
 String newPath =path.join(dir, 'new file name'); //rename
 print(newPath); //here the newpath
 file.renameSync(newPath);

這對我有用

String dir = (await getApplicationDocumentsDirectory()).path;
String newPath = path.join(dir,(DateTime.now().microsecond.toString()) + '.' + file.path.split('.').last);
File f = await File(file.path).copy(newPath);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM