I have Flutter app which needs to load dynamic assets and content which I want to save for later use. I know about Assets I can have in build time at the folder "assets/" inside the app.
I want to download content using ZIP files and unzip them to app local folder so they won't delete in the next app update.
what are the folders Flutter allows me to add assets to at runtime?
You cannot dynamically add assets to Flutter app at runtime and that is why Shared_Preferences package was developed by the official Flutter_Dev Team.
https://pub.dev/packages/shared_preferences
If you want to store a File instead of bits of information then refer to the below example code (For a Image File):
Future getImage(ImageSource imageSource) async {
// using your method of getting an image
final File image = await ImagePicker.pickImage(source: imageSource);
// getting a directory path for saving
final String path = await getApplicationDocumentsDirectory().path;
// copy the file to a new path
final File newImage = await image.copy('$path/image1.png');
setState(() {
_image = newImage;
});}
If your still want to somehow add/delete files dynamically then the answer is that it is practically not possible because assets weren't designed to dynamically store files.
One should only use assets to store files which shall remain common for all users.
Related
How do I save a file generated by my application to the downloads folder when using the WinUI 3 SDK? I know I can use FilePicker to select a file to use in my application but I would like to essentially do the opposite and save a file from my application somewhere or just simply put it into downloads.
This is an example saving the StoreLogo.png file, which is in the Assets folder by default, to the Downloads folder.
using Windows.Storage;
...
// Get the StoreLogo.png file as a StorageFile.
Uri storeLogoUri = new($"ms-appx:///Assets/StoreLogo.png");
StorageFile storeLogoFile = await StorageFile.GetFileFromApplicationUriAsync(storeLogoUri);
// Get the Downloads folder as a StorageFolder.
string downloadsFolderPath = UserDataPaths.GetDefault().Downloads;
StorageFolder downloadsFolder = await StorageFolder.GetFolderFromPathAsync(downloadsFolderPath);
// Save (copy) the StoreLogo.png file.
await storeLogoFile.CopyAsync(downloadsFolder);
Here is my use case:
I am getting the list of URLs of images.
I want to display and cache them in the database, not only for a particular session so for the next time it should not do a web service call.
Our app is working offline as well. I tried a few libraries like flutter_advanced_networkimage and flutter_cache_manager but I'm getting quite lag and most of the times app crash.
Save it in your app's temp directory:
import 'dart:io';
// https://pub.dev/packages/path_provider
import 'package:path_provider/path_provider.dart';
final Directory temp = await getTemporaryDirectory();
final File imageFile = File('${temp.path}/images/someImageFile.png');
if (await imageFile.exists()) {
// Use the cached images if it exists
} else {
// Image doesn't exist in cache
await imageFile.create(recursive: true);
// Download the image and write to above file
...
}
It will persist through app launches and only gets deleted when the user personally clears the cache or reinstalls the app.
I've been using cached_network_image, works as advertised
I have this to upload photos:
module.exports = function (req, image, url, callback) {
var filename = (Math.floor((Math.random() * 100000000000) + 1)) + ".png";
req.file(image).upload({
dirname: '../../assets/images' + url
,
saveAs: function(file, cb) {
cb(null, filename);
}
}, function(error, uploadedFiles) {
return callback(null, "http://" + req.headers.host + "/images" + url + filename)
});
}
And it returns an url like this: http://localhost:1349/images/dependent/photos/30363010266.png
I can see that my photo is uploaded in project folder because I see it physically. But the URL do not work and has appeared not found error.
If I restart server, the URL works fine.
Thanks!
As #Eugene Obrezkov pointed out, your issue is related to where you are uploading your images and the grunt task runner. All the assets are copied from that folder (/assets) to the .tmp, and changes are watched by the grunt task runner, but that doesn't include new image files(If you are to an empty folder in the assets folder, in your case to the image folder). So the solution is quite easy, you must upload directly to the .tmp folder, ideally to .tmp/public/uploads/year/month/, you can choose your path as you see fit. Now there is a caveat with this approach, and it is that there is a grunt task that clears the contents of the .tmp folder on sails lift, so you will get the opposite effect, now to avoid this is quite easy too, you must edit the clean.js task to delete specific folders, to avoid deleting your uploads folder.
Go to to your project folders tasks/config/clean.js, and replace what's in there for this code, or modify it as you need.
module.exports = function(grunt) {
grunt.config.set('clean', {
dev: [
getFolderPath('fonts/**'),
getFolderPath('images/**'),
getFolderPath('images/**'),
getFolderPath('js/**'),
getFolderPath('styles/**'),
getFolderPath('*.*')
],
build: ['www']
});
grunt.loadNpmTasks('grunt-contrib-clean');
};
function getFolderPath(folderName){
return '.tmp/public/' + folderName;
}
Now your uploads will appear immediately to your end-user without restart, and restarts won't delete those uploads. Just make sure the .tmp/public/uploads/ path exist before trying to upload, or use mkdir to create it via code if not found.
There are other solutions, like making sure there is at least a file in the folder you are uploading to when the server starts, or using symlinks, but i think this is a cleaner approach. You can check those options here:
Image not showing immediately after uploading in sails.js
If you take a look into tasks folder, you can find Grunt task that copies all the assets folder to .tmp folder and make .tmp folder as static public folder.
When you are running Sails application, it runs these Grunt tasks, so that if you uploading file direct to assets folder it will not be accessible until you re-run server and Grunt tasks.
Solution? There is no solution. Basically, you are doing it wrong. Best practices is to store images\files\whatever on S3 buckets, Google Storage, another hard drive at least, but not assets itself. Because it's your source files of your project and in there should be located only files needed for project itself, not user's files, etc...
You can achieve without modifing any grunt task. I had the same issue and I have just solved it.
I see you already have an explanation of what's happening in other comments, so I'll go straight to my solution. I uploaded the files to the .tmp folder, and on the callback of the upload, I coppied them to the assets folder using the file system (fs-extra is a great package for that).
So now I can see the images in my UI as soon as it's added (cause I uploaded them to .tmp) and when my server stops, .tmp will be lost, but generated again in the next lift with the files copied to assets.
Hope it helps!
This is how I solved this problem. The answer requires several steps. I am assuming you want to place your recently uploaded images in a folder called users.
Steps:
1. npm install express --save (If you don't have it installed)
Create a Users folder in your apps root directory.
Open the text editor and view the following file config\express.js
Add or replace with the code
`
var express = require('express');
module.exports.http = {
customMiddleware: function (app) {
app.use('/users', express.static(process.cwd() + '/users'));
}
};
`
5. Make certain the newly uploaded images are placed in the Users folder
Finish
I am going through http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/images/
and trying to get the Local Images working with Android however I am experiencing some issues when attempting to do something in normal monodroid just as a further test. I'm using a SharedProject, just for reference.
I have added the test image at Resources/drawable (test1.png), and also setting the Build Action as AndroidResource as it describes, and if I do the following in Xamarin.Forms it works:-
Xamarin.Forms.Image myimage = new Image();
myimage.Source = ImageSource.FromFile("test1.png");
However, if I try and retrieve the same file via the following it comes back as null.
Android.Graphics.Bitmap objBitmapImage = Android.Graphics.BitmapFactory.DecodeFile("test1.png")
Does anyone know why this is null and how to correct?
The Xamarin.Forms FileImageSource has a fallback mode as it covers two different scenarios.
First it will check whether the file exists in the file system via the BitmapFactory.DecodeFile.
Should the file not exist as specified in the File property, then it will use BitmapFactory.DecodeResource to try and load the resource content as a secondary alternative.
FileImageSource for Android therefore isn't only just for files that exist in the file system but also for retrieving named resources also.
This link indicates that Android Resources are compiled into the application and therefore wouldn't be part of the file system as physical files.
Since test1.png is a Drawable you should use BitmapFactory.DecodeResource ()
string scr = "#drawable/test1.png";
ImageView iv = new ImageView(context);
Bitmap bm = BitmapFactory.DecodeFile(src);
if (bm != null)
iv.SetImageBitmap(bm);
Is it possible to upload image or file to SkyDrive fom Metro Style App?
I have already found how to browse the file from SkyDrive. But I haven't found regarding uploading file to SkyDrive. If you reply me, it will be very thankful..
I don't think the file picker method works unless the user has the desktop app installed.
You should use a Sharing contract. If you add a data file (Storage Item) to share, then SkyDrive will be listed as a share target and the user gets a UI where they can choose where in their SkyDrive they want to save. This is how I implemented it in my app.
For more info...
http://msdn.microsoft.com/en-us/library/windows/apps/hh771179.aspx
You can use FileSavePicker to save files. This will of course give the user a chance to select where he wants to save to local documents folder or sky drive. The user is in control.
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.DefaultFileExtension = ".YourExtension";
savePicker.SuggestedFileName = "SampleFileName";
savePicker.FileTypeChoices[".YourExtension"] = new List<string>() { ".YourExtension"};
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
await FileIO.WriteTextAsync(file, "A bunch of text to save to the file");
}
Please note that in the sample code I am creating the content of the file in code. If you want the user to select an existing file from the computer then you will have to first use FileOpenPicker, get the file and then use FileSavePicker to save the contents of the selected file to the SkyDrive
Assuming that you are using XAML/JavaScript, the suggested solution is to use FilePicker.
The following link may help you.
http://msdn.microsoft.com/en-us/library/windows/apps/jj150595.aspx
Thanks Mamta Dalal and Dangling Neuron, but there is problem. But it looks like I can't use FileSavePicker. I have to upload file(documnet, photo) not only text file. I have to copy from one path to another. If I use FileSavePicker, I have to write every file content (text, png, pdf, etc) and can't copy. Currently I am using FolderPicker. But unfortunately, FolderPicker doesn't support SkyDrive.My Code is As follow:
>FolderPicker saveFolder = new FolderPicker();
>saveFolder.ViewMode = PickerViewMode.Thumbnail;
>saveFolder.SuggestedStartLocation = PickerLocationId.Desktop;
>saveFolder.FileTypeFilter.Add("*");
>StorageFolder storagefolderSave = await saveFolder.PickSingleFolderAsync();
>StorageFile storagefileSave = [Selected storagefile with file picker];
>await storagefileSave.CopyAsync(storagefolderSave,storagefileSave.Name,NameCollisionOption.ReplaceExisting);
It will be greate that if FolderPicker supports SkyDrive or can copy file using FileSavePicker.