I am using the capacitor FileSystem to save and load a file.
I save the file :
const savedFile = await Filesystem.writeFile({
path: fileName,
data: this.iconAvatarBase64,
directory: Directory.Data
});
this.iconAvatarUrlLocalRaw = fileName;
this.iconAvatarUrlLocal = savedFile['uri'];
I am using the file in src like this :
getIconAvatarUrlLocal() {
return Capacitor.convertFileSrc(this.iconAvatarUrlLocal);
}
<img slot="start" class="avatar menu" [src]="sanitizer.bypassSecurityTrustUrl(obj.getIconAvatarUrlLocal())">
When I launch the application I create the file, then save the data locally. I can display the image without problem, I can stop/relaunch the apps, the file is working.
But if I rebuild my apps in Xcode, then the file is not working, the img block can't display its. The saving data is used, consequently the image is not recreated, the link is known.
On web browser and Android I do not have this bug.
The strange part is that "stat" is working ...
await Filesystem.stat({ path: this.iconAvatarUrlLocalRaw, directory: Directory.Data});
Consequently the file exist but img can't access to the file ...
An exemple :
Working : I create the file capacitor://localhost/capacitor_file/var/mobile/Containers/Data/Application/E3BBB3DA-E64B-414F-B67C-34DB4A3D54DD/Documents/animalIconAvatar_32_659.5026582928432.svg
Not working : After I rebuild in Xcode : capacitor://localhost/capacitor_file/var/mobile/Containers/Data/Application/E3BBB3DA-E64B-414F-B67C-34DB4A3D54DD/Documents/animalIconAvatar_32_659.5026582928432.svg
Working : I re-create the file : capacitor://localhost/capacitor_file/var/mobile/Containers/Data/Application/2F3FC606-48CF-4C51-8EF3-BE7D9B350958/Documents/animalIconAvatar_32_960.997327389742.svg
I have 2 methods to solve my problem but I have no idea how to implement them :
Rebuild the image if the image is not working. Stat works, consequently I do not know how to do detect the image is not working.
Having the link working after rebuild in Xcode
I someone has an idea, I am stuck with this.
Solution,
To check if the file exist I use :
Capacitor.convertFileSrc(await Filesystem.getUri({ path: fileName, directory: Directory.Data})['uri']) !== undefined
Related
I am trying to programmatically create an ePub file. I am following this tutorial. The tutorial says to "make the .epub container that all these files go in" by:
Create an empty .zip file with whatever name you like (See notes below for detailed instructions on how to do this.)
Copy the mimetype file into the zip file (don't use compression on this file)
Copy the rest of the files and folders mentioned above into the zip file *
Re-name the .zip extension to .epub
These are the last few steps of the process. I have all the files that need to go into the zip ready. I know the files work because I used a third party program (eCanCrusherMac.1.2.1) to do these finals steps and the product it creates is an ePub file that loads in the Books eReader (made by Apple).
I used the below code to zip the desired directory. I found this code on here Stack Overflow
func zip(itemAtURL itemURL: URL, in destinationFolderURL: URL, zipName: String) throws {
var error: NSError?
var internalError: NSError?
NSFileCoordinator().coordinate(readingItemAt: itemURL, options: [.forUploading], error: &error) { (zipUrl) in
// zipUrl points to the zip file created by the coordinator
// zipUrl is valid only until the end of this block, so we move the file to a temporary folder
let finalUrl = destinationFolderURL.appendingPathComponent(zipName)
do {
try FileManager.default.moveItem(at: zipUrl, to: finalUrl)
} catch let localError {
internalError = localError as NSError
}
}
if let error = error {
throw error
}
if let internalError = internalError {
throw internalError
}
}
I took the file this function gives me, made sure it had the epub extension and tried to open it using the Books app but it fails to load. The code produces a zip file that I can interact with normally in Finder so I know the function works.
I believe the issue is with the "mimetype" file getting compressed. I have taken a valid ePub, changed the file's extension to zip, unzipped it and then rezipped it using Finder and tried to open it again with no other changes and it doesn't work. As you can see in the instructions from the tutorial at the top of this post the "mimetype" file can't be compressed.
This is a Swift app on Mac.
I looked into the different NSFileCoordinator.ReadingOptions and NSFileCoordinator.WritingOptions and searched on Stack Overflow and elsewhere online but I can't find anything on how to create a zip file in Swift without compressing a file contained in the zip file.
I was able to get the ePub to open using ZIPFoundation:
try FileManager.default.zipItem(
at: bookURL,
to: ePubURL,
shouldKeepParent: false,
compressionMethod: .none,
progress: nil
)
I have a sales app develpmented in Flex Builder. For use photos by off-line way, i upload a compressed file with all photos to the site and when need i sincronize with my smartphone. In that process is made a download to the dispositive and exist a responsable plugin to descompress the archive and disponibilize it in apropriate folder to later use.
That compressed file has 500MB size - 6700 photos approximately - and in Flex i have no type of problem to do that.
I'm rewriting the app in Flutter, using a archive package, dont getting the same results. In the descompress process i have problem with Out of memory.
Somebody already faced for something like that ?
Is there an best way to do this ?
I already tried other two alternatives:
- To use the Image.network, but, one of requires is work off-line.
- To save all the photos in assets folder, but i think that is not the best alternative, because the app will get bigger
Thank you in advance for.
Follow the error message and the code
code:
unarchiveAndSave()async{
var zippedFile = await initDir();
var bytes = zippedFile.readAsBytesSync();
var archive = ZipDecoder().decodeBytes(bytes);
for (var file in archive) {
var fileName = '$_dir/${file.name}';
if (file.isFile) {
var outFile = File(fileName);
print('File:: ${outFile.path}');
outFile = await outFile.create();
await outFile.writeAsBytes(file.content);
}
}
print('terminei de descompactar os arquivos');
}
The goal is to:
1) Allow the user to choose a picture [I use image_picker for that]
2) User crops image to a 1:1 aspect ratio [I use image_crop for that]
3) Upload image to Python backend
The problem:
After cropping image, attempting to read the image to Post it returns:
Unhandled Exception: FileSystemException: Cannot open file, path = '/data/user/0/com.example.AppName/cache/image_crop_26d4daef-e297-456c-9c6d-85d2e4c0d0662042323543401355956.jpg' (OS Error: No such file or directory, errno = 2)
The weird part is, I can display the image just fine within Flutter using `FileImage(_imageFile)' (considering _imageFile is the File variable)
It's just that I cannot use _imageFile.length() or even base64Encode(_imageFile.readAsBytesSync()).
Any ideas on what's happening and how to fix it?
path_provider plugin supports access to two filesystem locations:
Temporary directory,
Documents directory.
— The temporary directory is the cache and its content may be erased by the system at any time. So, storing data here is not good for us to get it later.
— The documents directory is the one we to choose now, this is a directory for the app to store files that only it can access
And You are using temporary directory (/data/user/0/com.example.AppName/cache/image_crop_26d4daef-e297-456c-9c6d-85d2e4c0d0662042323543401355956.jpg)
And if file is not erased then you can use following snippet to read file content:
final directory = await getTemporaryDirectory();
// For your reference print the AppDoc directory
final path = directory.path;
final file = File('$path/data.txt');
String contents = await file.readAsString();
return contents;
I have a text file that I will be reading and writing to. I have gotten the code to read successfully, but am unable to write to the text file again. I want to overwrite everything (not amend).
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent("airports.txt")
var strTextToWrite:String = String()
strTextToWrite = "Test"
do {
try strTextToWrite.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch { print("Error") }
}
The above code doesn't throw an error (i.e. the word 'Error' isn't printed as per my catch code), but the text file remains unedited, retaining the value it had before the code was run.
The text file is contained inside the X-Code project as shown below:
I'm at a real loss here, I don't understand why the code isn't working. I have confirmed that it is being run (by printing the value of strTextToWrite before and after the do statement, and it is definitely running through the do block of code because it isn't being caught by the catch block. The only thing I can think of is that the code is pointing at the wrong file (but the file name is correct, as you can verify with the screenshot above).
What am I doing wrong? Thanks in advance.
You are looking at 2 different files: the one you write to is ~/Documents/airport.txt while the one you see (and check) in Xcode is located in your project folder. To see the update, you need to reference the file in Xcode, not make a copy of it.
Right click airport.txt in your Project Navigator and click Delete > Move to Trash
Go to ~/Documents/airport.csv and drag it into your Xcode project. Do not add it to any target and unselect "Copy Items if Necessary"
You now have created a link to the file.
Modifying files in your bundle is generally a bad idea. If you need a place to output a temporary file, use the app's subfolder under ~/Application Support or the system's temp folder.
I have developed a C# application, in the application the users choose a photo for each record. However the user should also be able to change the pre-selected photo with a newer one. When the user changes the photo the application first deletes the old photo from the application directory then copies the new photo, but when it does that the application gives an exception because the file is used by the application so it cannot be deleted while the application is running. Does any one have a clue how to sort this out? I appreciate your help
This is the exception
The process cannot access the file
'D:\My
Projects\Hawkar'sProject\Software\Application\bin\Debug\Photos\John
Smith.png' because it is being used by
another process.
//defining a string where contains the file source path
string fileSource = Open.FileName;
//defining a string where it contains the file name
string fileName = personNameTextBox.Text + ".png" ;
//defining a string which specifies the directory of the destination file
string fileDest = dir + #"\Photos\" + fileName;
if (File.Exists(fileDest))
{
File.Delete(fileDest);
//this is a picturebox for showing the images
pbxPersonal.Image = Image.FromFile(dir + #"\Photos\" + "No Image.gif");
File.Copy(fileSource, fileDest);
}
else
{
File.Copy(fileSource, fileDest);
}
imageIDTextBox.Text = fileDest;
First of all, you code is not good.
The new image is only copied if there is currently no image (else).
But if there is an old image, you only delete this image, but never copy the newer one (if).
The code should better look like this:
if (File.Exists(fileDest))
{
File.Delete(fileDest);
}
File.Copy(fileSource, fileDest);
imageIDTextBox.Text = fileDest;
This code should work, but if you are getting an exception that the file is already in use, you should check "where" you use the file. Perhaps you are reading the file at program start. Check all parts of your program you are accessing these user files if there are some handles open.
Thanks a lot for your help and sorry for the mistake in the code I just saw it, my original code is just like as you have written but I don't know maybe when I posted accidentally I've put like this. when the application runs there is a picturebox which the image of each record is shown, that is why the application is giving an exception when I want to change the picture because it has been used once by the picturebox , however I've also tried to load another picture to the picture box before deleting the original one but still the same. I've modified the above could if you want to examine it