uri path is invalid - android

I'm working on a flutter app and part of the configuration asks for the url, I've installed the web admin interface on a subdomain.
static const String api_url = "app.sitename.co.uk/api/";
I issue the command flutter run which throws this:-
The following ArgumentError was thrown resolving an image codec:
Invalid argument(s): No host specified in URI
If I move the web admin to sitename.co.uk/app/api I then get the following error:-
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Invalid character (at character 16) asitename.co.uk/app/api which is the forward slash
I don't want to run the web admin interface inside my root directory, I would rather run it on the subdomain or inside another folder under my root. Does anybody know why the app would throw these errors and how I resolve it?
Thanks

Using URL's typically you'd want to initialise it with the URI class, rather than String;
void main() {
String _url = 'app.sitename.co.uk';
Uri url = Uri(host: _url, scheme: "https", path: 'api');
print(url);
}
DartPad example
Output:
https://app.sitename.co.uk/api
Depending on how you're using the String URL (if a library is used) It might be that the specific library doesn't handle URL parsing from just a String and requires it as a URI object.

Related

Android webview - how to pass a large binray file to Javascript

I have a mobile app that wraps around the web-app, using webview.
The web-app has a button to open a large .zip file (e.g. 100 MB).
The user clicks a button, and selects a .zip file.
This triggers an onChange function with a variable of type File (Blob), which includes attributes like:
file name
file size
file type (application/zip)
The javascript code then parses the .zip file, extracts specific data within it and uses it within the web-app.
This works well within the web-app, when the app is called via the Chrome browser.
For example when operated in chrome browser on an Android phone, I can pull the .zip file and open it in the web-app.
I want to do the same but using the mobile app.
I am able to pick up the .zip file using a File Chooser, but I have problems to fetch the file from the Javascript code.
When calling fetch(fileUri) from the Javascript side I'm getting errors.
I'm using the following uri
/storage/emulated/0/Android/data/com.example/files/Download/file2.zip
The fetch succeeds but returns a blob with size of 165 (i.e. not the actual size of the file) which hosts the error message:
{
"error": "Not Found",
"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
}
The program flow is like so:
I select a .zip file via FileChooser.
In onActivityResult, the uri value is /document/msf:12858 (seen via uri = intent.getData();)
The uri needs to be mapped into a real path file url, such that the fileUrl will be passed to Javascript (via webview).
Javascript will then fetch the file using the fileUrl.
I searched how to get the real path file url when selecting a file with FileChooser, and found
this, and this links.
I wasn't able to get the real file path, so I decided to read the file and write it to another location, so I can get a file path. (this is not efficient and done just to check the functionality).
I create the new file using the following code:
InputStream stream = context.getContentResolver().openInputStream(uri);
File file2 = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "file2.zip");
writeBytesToFile(stream, file2);
I don't see any errors when creating the file, and when creating the file, the number of bytes that are read and written to the new file are as expected.
For file2, I get a value of:
/storage/emulated/0/Android/data/com.example/files/Download/file2.zip
Then, within the Javascript code I fetch this file path.
But I'm getting a Blob with the "file-not-found" content as above.
So:
How can I verify that the file is indeed created and that the path can be fetched from Javascript?
How can I get the real file path of the original selected file, so I don't have to read and write the original file to new location just to get the file path?
Thanks
EDIT1:
I have "Intent intent" and not "Intent data" in the signature of onActivityResult.
I replaced String filePath = intent.getData() with
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
try {
intent_to_resolve = new JSONObject();
if (resultCode == RESULT_OK) {
// try1
String filePath1 = intent.getData().toString();
Log.d("Verbose", "filePath1: " + filePath1);
// try2
String filePath2 = intent.toString();
Log.d("Verbose", "filePath2: " + filePath2);
...
I'm getting the following value for filePath:
filePath1: content://com.android.providers.downloads.documents/document/msf%3A12858
filePath2: Intent { dat=content://com.android.providers.downloads.documents/document/msf:12858 flg=0x43 }

Trouble loading local html file into default device browser in Android app

I am an iOS developer assigned a task in Android, so bear with me, I'm a bit green in Android.
I am attempting to load a local html file that is stored in the device download directory in a folder called user_guide. I want the html file to load in the device's browser (not in a webview for reasons outside the scope of this post). I am using the following code to launch the browser:
String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
String path = "file://" + downloadPath + "/user_guide/index.html"; // + R.raw.test;
Uri pathUrl = Uri.parse(path);
Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
browserIntent.setData(pathUrl);
context.startActivity(browserIntent);
I obtained the value of path by setting a breakpoint and manually set it in Chrome on my device to verify that is does work and loads the proper file. However, when I try to run this code in the app, I get the following toast message:
Cannot display PDF (index.html is of invalid format)
I'm confused about this message since I am trying to load an html file, not a PDF. Can anyone help me out? THanks!
Try changing "browserIntent.setData(pathUrl)" to
browserIntent.setDataAndType(pathUrl, "text/html")
to explicitly specify that it's HTML.
I found this suggestion at https://stackoverflow.com/a/7009685/10300291.

Read a "TXT" file in Dart

i was trying to read a .txt file (from assets) in items of a list, so i was doing this:
list.add(await rootBundle.loadString('assets/jolo.txt'));
It takes the whole document and put it in 'data', but at showing the list is empty.
So i tried something else:
new File('assets/jolo.txt')
.openRead()
.transform(utf8.decoder)
.transform(new LineSplitter())
.forEach((l) => list.add(Item(name: l)));
but that throws me an error:
FileSystemException: Cannot open file, path = 'assets/jolo.txt' (OS Error: No such file or directory, errno = 2)
What can i do? I'm using plain text for putting every line into an item for show the whole list
To load an asset you must use the bundle. loadString takes care of reading the asset and dealing with the encoding so you get a String. Use LineSplitter.convert on the string:
String jolo = await rootBundle.loadString('assets/jolo.txt');
List<Item> list =
LineSplitter().convert(jolo).map((s) => Item(name: s)).toList();
You may not be running in the directory that you think.
Try looking at Directory.current() to see where you are running.

How to download file with new Dropbox API?

Dropbox now have an apsolutely new API, which is absolutely differ from the old one (it's interesting why), but there's no ANY actual examples in the internet, so I've found only some code in their examples. Here is it:
// Download the file.
try (OutputStream outputStream = new FileOutputStream (file)) {
mDbxClient.files ()
.download (metadata.getPathLower (), metadata.getRev ())
.download (outputStream);
}
I need to download file from remote folder to the local one, so I need to use this path for example:
.download ("Backups/backup.ab", "/storage/sdcard/Folder/backup.ab")
I've tried it, but get a error
IllegalArgumentException: String 'rev' does not match pattern'
Do you know, what it can be, and metadata.getPathLower () and metadata.getRev () methods are using for? I've learned, that metadata var gets from the first argv from execute (), but what this functions do?
Thanks a lot!
Not sure if if works for android. I have posted the following method just in case someone is looking for a C# .net solution.
private async Task Download(DropboxClient dbx, string folder, string file, string localFilePath)
{
using (var response = await dbx.Files.DownloadAsync(folder + "/" + file))
{
using (var fileStream = File.Create(localFilePath))
{
(await response.GetContentAsStreamAsync()).CopyTo(fileStream);
}
}
}
Parameter example:
file = "YourFileName.pdf";
folder = "/YourDropboxFolderName";
localFilePath = #"C:\Users\YourUserName\YourFileName.pdf";
The Dropbox API v2 Java SDK's download method takes these two parameters:
String path
String rev
Per the download method documentation there, the first is the remote path of the file in Dropbox you want to download, and the second is the identifier for the revision of the file you want. The second parameter is not the local path where you want to save the file, as it appears you're supplying in your code. Instead, you save the file content using the .download (outputStream); portion of the sample code you posted, e.g., as also shown in this sample code.
Also, as stated in the documentation, the second parameter is deprecated and should no longer be used. You can just use the version of the download method that only takes the one parameter. The code for using it is otherwise the same as the sample.
For reference, in the sample, the metadata object is an instance of FileMetadata. You can find more information on the getPathLower and getRev methods in the documentation as well.

Downloading a pdf blob to device in Cordova Android App

I am working on a program where I want to save a pdf blob in a android device.
This is server side code inside a callback which receives pdf data as 'result'.
var file = new Blob([result.data], {
type: 'application/pdf;charset=utf-8;'
});
return file;
});
At client side, the following code works in chrome debugging browser and pdf is successfully downloaded. However on device I get the following error :
11-18 18:13:27.255 10504-10707/? D/FileTransfer: download blob:file:///e9088aac-8525-4071-9280-164a6e15c22e to file:///storage/emulated/0/Download/loanContract_11-10-2016_9-29-59-715.pdf
11-18 18:13:27.255 10504-10707/? E/FileTransfer: Unsupported URI: blob:file:///e9088aac-8525-4071-9280-164a6e15c22e
Here the data in window.URL.createObjectURL(data) is the file blob returned by server. Phonegap/Cordova 3.6 - Download of file through blob:file didnt help me in solving the problem.
var fileURL = window.URL.createObjectURL(data);
$scope.content = data;
a.href = fileURL;
a.download = fileName;
a.click();
console.log("Inside parent function");
$scope.fileName = fileName;
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, function (dirEntry) {
download($scope.fileURL, dirEntry.toURL()+'Download/'+ $scope.fileName) ;
}, function () {} );
var download = function ( uri, fileURL) {
$cordovaFileTransfer.download(
uri,
fileURL,
function (success) {
console.log(success);
},
function (err) {
console.log(err);
}, true)
};
If i give a url which sends a pdf file as HTTP response and I provide the API's URL as the parameter uri to cordovaFileTransfer.download, then the pdf gets saved.
Kindly help me saving this bob as a pdf on the device.
First, get the file by requesting the file system and then download it from your server with fileTransfer.download(). After completing the download call the FileOpener (which will open a pop up where to choose from apps like Adobe Reader). Note: Make sure to include the FileTransfer feature via CLI/Terminal:
cordova plugin add cordova-plugin-file --save
Navigate to your project folder
Open CLI/Terminal and type in:
cordova plugin add
https://github.com/don/FileOpener.git
After successful download and storage of your file on the device (see
above) you open it with:
window.plugins.fileOpener.open("file:///sdcard/Android/data/com.example.application/document.doc")
or the appropriate path on iOS.

Categories

Resources