how to rename or delete file in local storage using flutter - flutter

I am developing an audio player using flutter.
In this project, I am using on_audio_query package to list all audio files from my mobile, then select one to play it.
I want to know, is there anyway to rename a file or delete it?
So the user can select one file and rename it, or select one or multiple files and delete them.
Thanks in advance

Try this example:
Future 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);
}

Use permission_handler to get access to manage_external_storage before..
Don't forget to add it in manifest
You can also use the shared storage to get access..
By using i think saf package

Related

How can I read and Write Files in Flutter Web?

I am working on flutter-web, I would like to do file operations(read and write) in flutter-web.
For Android and IOS, I was using path_provider dependency. But in Flutter-web, it is not supported.
Can anyone help me with this?
The accepted answer is not completely right. Yes, dart:io is not available on the web, but it is still possible to read files. You can select a file through the system's file picker and read it afterward.
An easy option to "write" a file is to send the user an auto-download.
Read:
Use this library to select a file: pub.dev/packages/file_picker (Web migration guide)
import 'dart:html' as webFile;
import 'package:file_picker_web/file_picker_web.dart' as webPicker;
if (kIsWeb) {
final webFile.File file = await webPicker.FilePicker.getFile(
allowedExtensions: ['pd'],
type: FileType.custom,
);
final reader = webFile.FileReader();
reader.readAsText(file);
await reader.onLoad.first;
String data = reader.result;
}
Write (a.k.a download):
import 'dart:html' as webFile;
if (kIsWeb) {
var blob = webFile.Blob(["data"], 'text/plain', 'native');
var anchorElement = webFile.AnchorElement(
href: webFile.Url.createObjectUrlFromBlob(blob).toString(),
)..setAttribute("download", "data.txt")..click();
}
in the dart docs it has been explained ... dart:io is not available to web build ... it means that you can not directly access to system files in flutter web . the build will fail .. you need to remove the code in order to run it
this is a security thing .. js doesn't allow it too .. imagine a website that can read all your system files if you visit it .. that's why things like path reading or file reading is not allowed .. it goes same for flutter
hope you have your answer
I created a package specifically for this before Flutter web was a thing. https://pub.dev/packages/async_resource
It looks at things as either a network resource (usually over HTTP), or a local resource such as a file, local storage, service worker cache, or shared preferences.
It isn't the easiest thing in the world but it works.
What about "dart:indexed_db library", You can store structured data, such as images, arrays, and maps using IndexedDB. "Window.localStorage" can only store strings.
dart:indexed_db
Window.localStorage
When it comes specifically to reading a file from disk on web, the easiest way is to use a PickedFile like so:
PickedFile localFile = PickedFile(filePath);
Uint8List bytes = await localFile.readAsBytes();

Iterating and reading text files from folder on Android

I made a word game app for android in Unity, where the player has to find a word from a category previously loaded to the game.
The way I load the categories is:
There is a folder named Categories, inside Assets, I run through the folder and read each text file as a category.
The categories are stored in a dictionary where the key is name the of the file and the value is every line of the file as an array element.
It worked well on the PC however no luck on android. Tried changing the path to
"public string categoriesDirectoryPath = Application.persistentDataPath +"Categories";" still does not work.
Original path was "Assets/Categories"
Code for initiating the dictionary with the file values is (Happens on GameManager's Awake()):
private Dictionary<string, string[]> createCategories(string directoryPath)
{
Dictionary<string, string[]> categories = new Dictionary<string, string[]>();
string[] categoryPaths = Directory.GetFiles(directoryPath);
foreach (string path in categoryPaths)
{
if (!path.EndsWith("meta")) {
Debug.Log(path);
string categoryName = Path.GetFileNameWithoutExtension(path);
Debug.Log(categoryName);
string[] categoryData = File.ReadAllLines(path).ToArray();
categories.Add(categoryName, categoryData);
}
}
return categories;
}
Is there a way of iterating the folder and reading the text files that were in Assets/Categories after building the APK?
Is there a way of iterating the folder and reading the text files that
were in Assets/Categories after building the APK?
No.
If you want to access from the project, in a build, you have two options:
1.Put the file a folder named "Resources" then use the Resources to read the file and copy it to the Application.persistentDataPath path. By copying it to Application.persistentDataPath, you'll be able to modify it. Anything in the "Resources" is read only.
2.Put the file in the StreamingAssets folder then use UnityWebRequest, WWW or the System.IO.File API to read it. Atfer this, you can copy it to the Application.persistentDataPath.
Here is a post with code examples on how to do both of these.
3.AssetBundle(Recommended due to performance and loading reaons).
You can build the file as AssetBundle then put them in the StreamingAssets folder and use the AssetBundle API to read it.
Here is a complete example for building and reading AssetBundle data.

How to load asset with same name, but placed in different folders from assetbundle?

I am using unity5.3.3, I would like to know how should I get the asset from an asset bundle, whose names are same but are kept in different folder. My AssetBundle Folder is set in the following manner:
MyAssets -> this Folder is packed as an AssetBundle
-ThemeOne(folder)
- Logo.png
-ThemerTwo(folder)
- Logo.Png
When I do AssetBundle.LoadAssetAsync("Logo"). I end getting the logo in the first(ThemeOne) folder. So how do I access the file in the other folder?
I have just created a sample project so that you can check it out. Check the Folder Assets\AssetBundleSample\SampleAssets\Theme and the script LoadAssets
You can put the ThemeOne(folder) and ThemeTwo(folder) in Resources Folder under assets and than use something like this
(AudioClip)(Resources.Load ("Sounds/" + "myaudioclip", typeof(AudioClip)) as AudioClip)
similarly load your png giving folder name first as i have given sounds and than name of file as i have given myaudioclip .
cast as texture or something as you want
As unity official docs provided
public string BundleURL;
public string AssetName;
IEnumerator Start() {
// Download the file from the URL. It will not be saved in the Cache
using (WWW www = new WWW(BundleURL)) {
yield return www;
if (www.error != null)
throw new Exception("WWW download had an error:" + www.error);
AssetBundle bundle = www.assetBundle;
if (AssetName == "")
Instantiate(bundle.mainAsset);
else
Instantiate(bundle.LoadAsset(AssetName));
// Unload the AssetBundles compressed contents to conserve memory
bundle.Unload(false);
} // memory is freed from the web stream (www.Dispose() gets called implicitly)
}
BundleURL will use the path where your actual assets is located. You can also use Application.dataPath in conjunction with ur specified path string.
Seems to be a bug. Still present in Unity version 5.3.3.
See: http://answers.unity3d.com/questions/1083400/asset-bundle-cant-have-multiple-files-with-the-sam.html
I'm not really sure if this is possible, you should read Explicit naming of assets which is FYI obsolete as on Unity 5.6. This allows you to explicitly name assets that you are including in the bundle. Alternatively, you could try,
bundle.LoadAsset("/Assets/ThemerTwo/Logo.png")
But generally, this is a bad practice to have assets of the same naming in the same bundle.
You can use the method LoadAssetAtPath() to specify the full path instead of just the asset name.
Example:
LoadAssetAtPath("Assets/Texture/Logo.jpg", typeof(Texture2D));
Documentation here: http://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html

Image not showing immediately after uploading in sails.js

In my application ,I have stored uploaded images to folder ./assets/uploads. I am using easyimage and imagemagick for storing the images.
In my application, after uploading the images, it should show the new uploaded image. But it is not displayed even if the page is refreshed. But when i do sails lift , the image is shown.
How to show image immediately after uploading the image? Thanks a lot!
It's a totally normal situation, because of the way Sails works with the assets.
The thing is that upon sails lift the assets are being copied (including directory structure and symlinks) from ./assets folder to ./.tmp/public, which becomes publicly accessible.
So, in order to show your images immediately after upload, you, basically, need to upload them not to ./assets/uploads but to ./.tmp/public/uploads.
The only problem now is that the ./.tmp folder is being rewritten each time your application restarts, and storing uploads in ./tmp/... would make them erased after every sails lift. The solution here would be storing uploads in, for example, ./uploads and having a symlink ./assets/uploads pointing to ../uploads.
Though this question is pretty old but I would like to add a solution which I just implemented.
Today I spend almost 4 hours trying all those solutions out there. But none helped. I hope this solution will save someone else's time.
WHY images are not available immediately after uploading to any custom directory?
Because according to the default Sails setup, you can not access assets directly from the assets directory. Instead you have to access the existing assets that is brought to .tmp/public directory by Grunt at time of sails lift ing
THE Problems
(Available but Volatile) If you upload a file (say image) anywhere inside .tmp/public
directory, your file (image) is going to erase at next sails lift
(Unavailability) If you upload a file in any other custom directory- say: ./assets/images, the uploaded file will not be available immediately but at next sails lift it will be available. Which doesn't makes sense because - cant restart server each time files gets uploaded in production.
MY SOLUTION (say I want to upload my images in ./assets/images dir)
Upload the file say image.ext in ./tmp/public/images/image.ext (available and volatile)
On upload completion make a copy of the file image.ext to ./assets/images/*file.ext (future-proof)
CODE
var uploadToDir = '../public/images';
req.file("incoming_file").upload({
saveAs:function(file, cb) {
cb(null,uploadToDir+'/'+file.filename);
}
},function whenDone(err,files){
if (err) return res.serverError(err);
if( files.length > 0 ){
var ImagesDirArr = __dirname.split('/'); // path to this controller
ImagesDirArr.pop();
ImagesDirArr.pop();
var path = ImagesDirArr.join('/'); // path to root of the project
var _src = files[0].fd // path of the uploaded file
// the destination path
var _dest = path+'/assets/images/'+files[0].filename
// not preferred but fastest way of copying file
fs.createReadStream(_src).pipe(fs.createWriteStream(_dest));
return res.json({msg:"File saved", data: files});
}
});
I dont like this solution at all but yet it saved more of my time and it works perfectly in both dev and prod ENV.
Thanks
Sails uses grunt to handle asset syncing. By default, the grunt-watch task ignores empty folders, but as long as there's at least one file in a folder, it will always sync it. So the quickest solution here, if you're intent on using the default static middleware to server your uploaded files, is to just make sure there's always at least one file in your assets/uploads folder when you do sails lift. As long as that's the case, the uploads folder will always be synced to your .tmp/public folder, and anything that's uploaded to it subsequently will be automatically copied over and available immediately.
Of course, this will cause all of your uploaded files to be copied into .tmp/public every time your lift Sails, which you probably don't want. To solve this, you can use the symlink trick #bredikhin posted in his answer.
Try to do this:
npm install grunt-sync --save-dev --save-exact
uncomment the line: // grunt.loadNpmTasks('grunt-sync');
usually it is near to the end of the file /tasks/config/sync.js.
lift the App again
Back to the Original answer
I was using node version 10.15.0, and I faced same problem. I solved this by updating to current version of node(12.4.0) and also updated npm and all the node modules. After this, I fixed the vulnerabilities(just run 'npm audit fix') and the grunt error that was coming while uploading the images to assets/images folder was fixed.
Try out this implementation
create a helper to sync the file
example of the filesync helper
// import in file
const fs = require('fs')
module.exports = {
friendlyName: 'Upload sync',
description: '',
inputs: {
filename:{
type:'string'
}
},
exits: {
success: {
description: 'All done.',
},
},
fn: async function ({
filename
}) {
var uploadLocation = sails.config.custom.profilePicDirectory + filename;
var tempLocation = sails.config.custom.tempProfilePicDirectory + filename;
//Copy the file to the temp folder so that it becomes available immediately
await fs.createReadStream(uploadLocation).pipe(fs.createWriteStream(tempLocation));
// TODO
return;
}
};
now call this helper to sync your files to the .temp folder
const fileName = result[0].fd.split("\\").reverse()[0];
//Sync to the .temp folder
await await sails.helpers.uploadSync(fileName);
reference to save in env
profilePicDirectory:path.join(path.resolve(),"assets/images/uploads/profilePictures/")
tempProfilePicDirectory:path.join(path.resolve(),".tmp/public/images/uploads/profilePictures/"),
also can try
process.cwd()+filepath

Mirth: How to get source file directory from file reader channel

I have a file reader channel picking up an xml document. By default, a file reader channel populates the 'originalFilename' in the channel map, which ony gives me the name of the file, not the full path. Is there any way to get the full path, withouth having to hard code something?
You can get any of the Source reader properties like this:
var sourceFolder = Packages.com.mirth.connect.server.controllers.ChannelController.getInstance().getDeployedChannelById(channelId).getSourceConnector().getProperties().getProperty('host');
I put it up in the Mirth forums with a list of the other properties you can access
http://www.mirthcorp.com/community/forums/showthread.php?t=2210
You could put the directory in a channel deploy script:
globalChannelMap.put("pickupDirectory", "/Mirth/inbox");
then use that map in both your source connector:
${pickupDirectory}
and in another channel script:
function getFileLastModified(fileName) {
var directory = globalChannelMap.get("pickupDirectory").toString();
var fullPath = directory + "/" + fileName;
var file = Packages.java.io.File(fullPath);
var formatter = new Packages.java.text.SimpleDateFormat("yyyyMMddhhmmss");
formatter.setTimeZone(Packages.java.util.TimeZone.getTimeZone("UTC"));
return formatter.format(file.lastModified());
};
Unfortunately, there is no variable or method for retrieving the file's full path. Of course, you probably already know the path, since you would have had to provide it in the Directory field. I experimented with using the preprocessor to store the path in a channel variable, but the Directory field is unable to reference variables. Thus, you're stuck having to hard code the full path everywhere you need it.