'Rename image that has been picked by imagepicker for flutter
I would like to rename the file that i already pick from my gallery by image picker, i already try the below method using renameAsync
String dir = path.dirname(pickedFile.path);
String newName = path.join(dir, 'customname.jpg');
File(pickedFile.path).renameSync(newName);
however it return error [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FileSystemException: Cannot rename file to ....
Solution 1:[1]
You have to do these steps:
- Convert XFile you get from ImagePicker to File
- Rename the File to what you want.
Here's the sample code:
result = await ImagePicker().pickImage(source: ImageSource.gallery, imageQuality: 50);
String newFileName = "mynewfilename.jpg"
# Convert Xfile to File
File resultFile = File(result!.path)
print(resultFile); // Old FileName with path
# Function to rename your File
File changeFileNameOnlySync(File file, String newFileName) {
var path = file.path;
var lastSeperator = path.lastIndexOf(Platform.pathSeparator);
var newPath = path.substring(0, lastSeperator + 1) + newFileName;
return file.renameSync(newPath);
}
File newFileResult = changeFileNameOnlySync(resultFile, newFileName);
print(newFileResult); // New FileName with path
You can convert it again to XFile to get an original file like the one you get from ImagePicker.
XFile newXFileResult = XFile(newFileResult.path);
print(newXFileResult);
print(newXFileResult.name);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
