Android Doesn't Recognize Image Downloaded by Flutter App - android

Android Flutter app downloads an image from a server on another Android phone. After downloading, the file is unable to be opened or viewed by the phones gallery or file explorer. However, when examined by a hex editor, the downloaded file and the original file are exact copies, and when imported to windows, the "corrupt" downloaded file is view able by the Image Viewer. The only difference I could find between the files was the metadata examined by Windows. What could be the cause of this?
Original File on Android Server:
Downloaded File On Android Client:
Here's the code I'm using to create the file from a Uint8list:
Future<File> downloadFileAndroid(Uint8List fileBytes, String fileName) async{
var dir = await getExternalStorageDirectory();
File photoFile;
var photoDirectory = await Directory(dir.path + "/Downloader").create(recursive: true);
photoFile = await new File(photoDirectory.path + "/" + fileName).create();
if(await photoFile.exists()){
await photoFile.writeAsBytes(fileBytes);// also tried flush: true
print("Created file and it exists");
} else {
print("Error: tried to create file but it doesnt exist");
}
}

I faced this problem when downloading an image from the internet and setting a png extention to it. Using an extention on the file name usually causes this error. Consider using https://pub.dev/packages/image_downloader to download the image using the default function in the example code. With the default option, the extension is not determined by the coder but instead by itself.

Related

Files to Base64 conversion using RNFS

Im trying to convert a file to base 64. for that im using react-native-document-picker and RNFS.
Problem: When files is picked thru
react-native-document-picker it gives me success and the path is temporary cache path. but when i try to convert it to base64 using RNFS it gives me that error.
it will pick file from iCloud but not which is showed as "On My iPhone" in file manager i think issue is its not pick images from local storage of iPhone.
ENOENT: no such file or directory, open '/private/var/mobile/Containers/Data/Application/A78E7E14-DBAC/tmp/com.xyz-Inbox/Scanned%20Document.pdf'
here's my code:
const response = await DocumentPicker.pickSingle({type: [DocumentPicker.types.allFiles],
copyTo: "documentDirectory" });
var data = await RNFS.readFile(response.uri, 'base64');
Thanks for help.

Xamarin.essentials FilePicker copies selected external file to cache folder

For the last 2 weeks I've been successfully converting a WPF application to a Xamarin.forms android app. Everything works as intended except for 1 thing. I've been searching the web for a few days for a solution but I can't find a working solution.
This is my current setup:
Xamarin.Froms android app
Target android version: Android 10.0
Minimum android version: Android 7.0
Xamarin.Essentials version: 1.6.0
READ_EXTERNAL_STORAGE permission
WRITE_EXTERNAL_STORAGE permission
My app should be able to open a selected file, using the Xamarin.Essientials FilePicker, Do some stuff and save the File again to the same path. The file selection is handled in the following code:
var pickresult = await FilePicker.PickAsync();
if (pickresult != null)
{
try
{
var result = await pickresult.OpenReadAsync();
var reader = new StreamReader(result);
var jsonstring = reader.ReadToEnd();
ConfigData = JsonConvert.DeserializeObject<ProjectData>(jsonstring);
PLC_Data.ProjectLoaded = true;
L_LoadedProject.Text = pickresult.FileName;
ProjectData.Filepath = pickresult.FullPath;
reader.Close();
result.Close();
//Load login page
B_Next.IsEnabled = true;
}
This is where the problem occurs. Let me clearify what happens step by step:
The FilePicker opens a File picking window.
I navigate to my preferred file in the "download" folder, could be any folder.
The file is read and converted to an object
The file path is saved
when i check the filepath i get the following string:
"/storage/emulated/0/Android/data/com.FAIS.motorconfigapp/cache/2203693cc04e0be7f4f024d5f9499e13/303bc84665374139b6303c03255e9018/config1.json"
So the FilePicker copies the "External" file to the App cache folder and returns the filepath from the Apps cache folder. When i check this folder there is indeed a copy of my selected file inside it. Reading from and writing to this file works as it should.
Now the actual question:
Why does the FilePicker copy my selected file to his cache folder and how can i prevent it?
The user should be able to select a file from anywere on the device and find the updated file in the same location.
I've checked all my settings and in my opinion everyting should be correct so i don't get why a copy is created. Does anyone have an idea?
If you need more settings, pictures, versions please ask.
Thanks in advance

Xamarin.Forms.Android: Populating 'Environment.SpecialFolder.Personal' with sample data files at compilation/deployment

My application records data from a patient monitor and stores it a '*.dat' file in 'Environment.SpecialFolder.Personal'.
The app also allows the user to 'play back' previously acquired recordings.
I wish to include a few sample 'dat' files within the apk. Is it possible to include such files as 'assets' in the project and have them copied to 'Environment.SpecialFolder.Personal' at the time of installation?
Copy the database into Assets folder.
And set the Build Action as AndroidAssect.
You could use the following code to copy the file from Assects folder to Android Application folder.
// Android application default folder.
var appFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var dbFile = Path.Combine(appFolder, "database.db3");
// Check if the file already exists.
if (!File.Exists(dbFile))
{
using (FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write))
{
// Assets is comming from the current context.
await Assets.Open(databaseName).CopyToAsync(writeStream);
}
}
Download the source file from the link below.
https://github.com/damienaicheh/CopyAssetsProject
Updated:
You could use the code below.
var assetName = "someasset.jpg";
var outputName = Path.Combine(Android.OS.Environment.DirectoryDownloads,
assetName);
using (var assetStream = context.Assets.Open(assetName))
using (var fileStream = new FileStream(outputName, FileMode.CreateNew))
{
await assetStream.CopyToAsync(fileStream);
}
If your device is higher than Android6.0, you need runtime permission.
https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/android-m-runtimepermissions/
For more details, please refer to the link below.
How to save file from assets on my device? Xamarin

phonegap download and save images from a url to the application installation folder

I am developing an application in phonegap that is supposed to work in both ios and android.
For this application i need to download all images from the server.I was able to download the images to the external memory card using the following code.
function storeIntelligrapeLogo() {
alert('start of file download');
var url = "http://www.kannuronlineservices.com/images/logo.png"; // image url
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
alert('inside request file sysytem')
var imagePath = 'file:///storage/sdcard0'+fs.root.fullPath + "/logo.png"; // full file path
alert('inside request file sysytem path fs.root==' + fs.root);
alert('inside request file sysytem path fs.root.fullPath==' + fs.root.fullPath);
var fileTransfer = new FileTransfer();
fileTransfer.download(url, imagePath, function(entry) {
alert(entry.fullPath); // entry is fileEntry object
}, function(error) {
alert("Some error" + JSON.stringify(error));
});
}) }
Now i would like this to work in ios also.For that what is the file path i have to use
for 'file:///storage/sdcard0'.Then now the file is downloaded to the external memory card in android and i would like it to be downloaded to the application installation folder and so that when the application is uninstalled,the images also get deleted.Or please suggest me if there exist some other way of doing this,ie:downloading images from server folder and storing it locally with phonegap so that the application is expected to work in offline mode also.
Thanks.
You can use a phonegap plugin.
Look at http://plugins.cordova.io/#/package/de.fastr.phonegap.plugins.downloader
It downloads multiple files to persistant storage on android and ios.

Display .mht file on android

How to display .mht(MHTML) file on android webview. I tried to open the .mht file on default android browser but that didn't open but i am able to open same on opera mobile browser. So i tried with MHTUnpack java library. I didn't succeed in that.
Here's a link!
Please if anybody has used this MHTUnpack let me how can i use that in android. And also let me know if there is any other library.
Thanks
Found this unknown google project which appears to be working.
This utility decodes the mhtml file and save it on given path(internal or external). After saving it returns the html file path which could be loaded into webview.
Try it.
After overcoming frustration about WebView.saveWebArchive() format change in Android 4.4, I tried the "unknown google project" Chitranshu Asthana mentioned in his answer, but code provided there is slow (~10s for 1MB *.mht file with a dozen of pictures) and doesn't handle attached file names correctly.
MHT Unpack library combined with Java Mail for Android (not the one provided by Oracle) worked perfectly for me.
EDIT: Fixed the link to MHT Unpack library. Also, here's usage example:
// contentPath - path to input .mht file
public static String unpackMht(String contentPath) throws IOException {
// dstPath - path where file will be unpacked
String dstPath = openTempDir(null) + File.separator;
String indexFileName = dstPath + new File(contentPath).getName();
try {
Collection<Attachment> attachments = MHTUnpack.unpack(new File(contentPath));
for (Attachment attachment : attachments) {
String filename = attachment.getFileName();
String path = filename == null ? indexFileName : dstPath + filename;
File newFile = new File(path);
if (newFile.exists()) {
newFile.delete();
}
attachment.saveFile(path);
}
return indexFileName;
} catch (MessagingException e) {
throw new IOException(e);
}
}

Categories

Resources