void getFileFromUrl(String uri) async {
var fileName = 'testonline';
try {
var _uri = Uri.parse(uri);
var data = await http.get(_uri);
var bytes = data.bodyBytes;
var dir = await getApplicationDocumentsDirectory();
File file = File("${dir.path}/" + fileName + ".pdf");
print(dir.path);
File urlFile = await file.writeAsBytes(bytes);
_pdfController = PdfController(document: PdfDocument.openFile(dir.path));
} catch (e) {
throw Exception("Error opening url file");
}
}
Hello I am developing website with Flutter,
I would like to present PDF file on my website.
getFileFromUrl(
'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');
I am calling this function in inistate on my web site, this link is the testing pdf link which is valid link.
But I am getting this error.
Error: Exception: Error opening url file
at Object.throw_ [as throw] (http://localhost:58701/dart_sdk.js:5037:11)
at membership_agreement_screen._MembershipAgreementScreenState.new.getFileFromUrl
(http://localhost:58701/packages/clio_application_portal/screens/membership_agreement_screen.dart.lib.js:1312:23)
at getFileFromUrl.throw (<anonymous>)
at http://localhost:58701/dart_sdk.js:37379:38
at _RootZone.runBinary (http://localhost:58701/dart_sdk.js:37249:59)
at _FutureListener.thenAwait.handleError (http://localhost:58701/dart_sdk.js:32511:48)
at handleError (http://localhost:58701/dart_sdk.js:33044:51)
at Function._propagateToListeners (http://localhost:58701/dart_sdk.js:33070:17)
at _Future.new.[_completeError] (http://localhost:58701/dart_sdk.js:32920:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:58701/dart_sdk.js:32956:31)
at Object._microtaskLoop (http://localhost:58701/dart_sdk.js:37497:13)
at _startMicrotaskLoop (http://localhost:58701/dart_sdk.js:37503:13)
at http://localhost:58701/dart_sdk.js:33274:9
Please let me know what is wrong...
I am waiting for you help..
Thanks for reading.
I would assume the problem is that this is a cross origin call, which is not allowed in a website. This has nothing to do with flutter though. But is a security feature enforced by the browsers.
If you want to serve some pdf file from another host than you are serving the JavaScript you have to either have control over the server hosting the PDF to add CORS headers, or add a reverse proxy on the same host of your JavaScript which proxies all requests.
Flutter describs this problem for images, but it just as well effects any http connections: https://flutter.dev/docs/development/platform-integration/web-images#cross-origin-images
Related
I'd like to download the JSON file which can be accessed by this url https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media. Every time I call the function I get a Error: XMLHttpRequest error. After some researches I found that this might be beacuase Google Firebase Storage is blocking it. Does anybody know how to avoid this block? I've read that I should whiltlist my local host? But how?
headers: {
HttpHeaders.authorizationHeader: 'Basic your_api_token_here', //here i want my token
},
But I have no clue how to get my api Token. Does anybody know how to fetch this token? May this error be caused becaus I run it on chrom flutter?
import 'package:http/http.dart' as http;
void testFunction(){
var url_string = "https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media";
var result = await getJsonFromFirebaseRestAPI(url_string);
print(result);
}
Future<String> getJsonFromFirebaseRestAPI(String url) async {
http.Response response = await http.get(Uri.parse(url));
return response.body;
}
The JSON file result should look like this:
routes: []
It's basically empty I'm just trying to implement the function.
I use http: ^0.13.5
I get the following error:
Error: XMLHttpRequest error.
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 299:10
createErrorWithStack
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 341:28
_throw
dart-sdk/lib/core/errors.dart 116:5
throwWithStackTrace
dart-sdk/lib/async/zone.dart 1378:11
callback
dart-sdk/lib/async/schedule_microtask.dart 40:11
_microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5
_startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15
<fn>
``
Can anybody solve my issue?
Appreciate your time :)
My app is using the image_picker plugin to let the user upload a profile picture from his phone and on Android everything works as expected.
The problem is that when I try to run the same code on web, it throws me the following error:
Error: AppwriteException: null, On web `bytes` is required (0)
at Object.throw_ [as throw] (http://localhost:42231/dart_sdk.js:5080:11)
at new input_file.InputFile.new (http://localhost:42231/packages/appwrite/src/input_file.dart.lib.js:79:17)
at database.DatabaseService.new.uploadProfilePic (http://localhost:42231/packages/presents/services/database.dart.lib.js:299:104)
at uploadProfilePic.next (<anonymous>)
at runBody (http://localhost:42231/dart_sdk.js:40660:34)
at Object._async [as async] (http://localhost:42231/dart_sdk.js:40691:7)
at database.DatabaseService.new.uploadProfilePic (http://localhost:42231/packages/presents/services/database.dart.lib.js:297:20)
at http://localhost:42231/packages/presents/screens/profile/show_profilepic_menu.dart.lib.js:262:33
at Generator.next (<anonymous>)
at http://localhost:42231/dart_sdk.js:40641:33
at _RootZone.runUnary (http://localhost:42231/dart_sdk.js:40511:59)
at _FutureListener.thenAwait.handleValue (http://localhost:42231/dart_sdk.js:35438:29)
at handleValueCallback (http://localhost:42231/dart_sdk.js:35999:49)
at Function._propagateToListeners (http://localhost:42231/dart_sdk.js:36037:17)
at _Future.new.[_completeWithValue] (http://localhost:42231/dart_sdk.js:35872:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:42231/dart_sdk.js:35906:35)
at Object._microtaskLoop (http://localhost:42231/dart_sdk.js:40778:13)
at _startMicrotaskLoop (http://localhost:42231/dart_sdk.js:40784:13)
at http://localhost:42231/dart_sdk.js:36261:9
I don't know if the problem is with the image_picker plugin or with AppWrite (the backend server), but since when I run the code in Debug mode it stops in the image_picker_for_web.dart file I'd guess the problem is with the former.
Actually, it stops on line 274 where it returns an XFile without the bytes parameter (see the code below), so maybe this is the problem? How can I fix that?
(the code of image_picker_for_web.dart I was talking about, from line 273)
if (!_completer.isCompleted && files != null) {
_completer.complete(files.map((html.File file) {
return XFile(
html.Url.createObjectUrl(file),
name: file.name,
length: file.size,
lastModified: DateTime.fromMillisecondsSinceEpoch(
file.lastModified ?? DateTime.now().millisecondsSinceEpoch,
),
mimeType: file.type,
);
}).toList());
}
Ok, after some further debugging I found out the problem was not with the image_picker package but with uploading the picked image on AppWrite storage.
Initially, I was uploading it with a code like this one:
Future<void> uploadProfilePic(XFlie file) async {
File res = await _storage.createFile(
bucketId: Constants.profilePicsBucketID,
fileId: 'unique()',
file: InputFile(
path: file.path,
filename: '$_uid.${file.path.split('.').last}',
),
read: ['role:all'],
);
}
And then I solved my problem passing the createFile function also a bytes parameter. So my final code is:
Future<void> uploadProfilePic(XFlie file) async {
List<int> fileBytes = await file.readAsBytes();
File res = await _storage.createFile(
bucketId: Constants.profilePicsBucketID,
fileId: 'unique()',
file: InputFile(
path: file.path,
bytes: fileBytes,
filename: '$_uid.${file.path.split('.').last}',
),
read: ['role:all'],
);
}
I'm trying to download *.xlsx file using dio.download, and it's throwing the errors:
Unhandled Exception: FileSystemException: Cannot open file, path = '/storage/emulated/0/Android/data/com.example.foodagator_app/files/file.xlsx' (OS Error: No such file or directory, errno = 2)
Another one error from try/catch block:
FileSystemException: Creation failed, path = 'File: '' (OS Error: Read-only file system, errno = 30)
I wrote the permission in androidmanifest for external storage, and also tried temporary directory, but it's not working. Can anyone help me with this? Here is my code
void download() async {
var tempDir = await getExternalStorageDirectory();
File file = File(tempDir!.path + '/file.xlsx');
try {
Response response = await dio.download(
url,
file,
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
),
);
var raf = file.openSync(mode: FileMode.write);
// response.data is List<int> type
raf.writeFromSync(response.data);
await raf.close();
} catch (e) {
print('Error is: $e');
}
}
void readFile() async {
var tempDir = await getExternalStorageDirectory();
var filePath = tempDir!.path + "/file.xlsx";
var bytes = File(filePath).readAsBytesSync();
var decoder = SpreadsheetDecoder.decodeBytes(bytes, update: true);
for (var table in decoder.tables.keys) {
print(table);
print(decoder.tables[table]!.maxCols);
print(decoder.tables[table]!.maxRows);
for (var row in decoder.tables[table]!.rows) {
print('$row');
}
}
}
This error is getting because there is no file named file.xlsx you can check if file exists or not
if(file.existsSync())
if file does not exist, you can create one using,
new File('$path/file.xlsx').create(recursive: true);
in android 11 and higher use below permission, without tools:ignore="ScopedStorage"
<uses-permission
android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
In my case, it was caused because I had moved a dart file to another folder but my other files were still referencing that file using the old path, you can import the file again using the new path and using the "package:" keyword to solve this error.
Moral: Don't use relative paths to import a file anywhere in your project, always use the "package:" scheme.
You could make a custom name as well.
String createDownloadDocName(){
return'${fileName}-${DateTime.now().microsecond}';
}
Sorry, I had problem with await usage - I tried to get access to file before I downloaded it
I am trying to login via Twitch and, to do that I am using https://pub.dev/packages/url_launcher and https://pub.dev/packages/uni_links. The code works well on iOS, but not on Android.
The process is:
Click on "Sign in with Twitch"
Opens a browser via launchUrl(_url)
Accept authorization of Twitch popup
Redirects to the callback of my backend server
Backend: Create/Retrieve the user
Backend: Returns a 307 HTTP with url: customscheme://auth/twitch?access_token=...
Listens the Deep Link: Close the browser and stores the token in the device
On Android, when my browser tries to redirect with my customscheme, the device browser returns an error:
Webpage not available
The webpage at
http://customscheme//auth/twitch?access_token=XXX
could not be loaded because:
net::ERR_NAME_NOT_RESOLVED
The customscheme is replaced by mine, and it works when I test it with the command:
adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "customscheme://auth/twitch".
So it seems it does not understand the custom scheme from the webview, and handle it like a simple HTTP url.
Here is my code:
void logWithTwitch() async {
assert(dotenv.env['TWITCH_CLIENT_ID'] != null);
assert(dotenv.env['TWITCH_REDIRECT_URI'] != null);
final String twitchClientId = dotenv.env['TWITCH_CLIENT_ID']!;
final String twitchRedirectUri = dotenv.env['TWITCH_REDIRECT_URI']!;
final List<String> scopes = [
'user:read:email',
];
final Uri _url = Uri(
scheme: 'https',
host: 'id.twitch.tv',
path: 'oauth2/authorize',
queryParameters: {
'client_id': twitchClientId,
'redirect_uri': twitchRedirectUri,
'response_type': 'code',
'scope': scopes.join(' '),
'force_verify': 'true',
});
if (await canLaunchUrl(_url)) {
await launchUrl(_url);
} else {
print('cannot open url');
}
}
...
_sub = linkStream.listen((String? link) {
if (link == null) {
return;
}
final _url = Uri.parse(link);
if (_url.host == 'auth' && _url.path == '/twitch') {
closeInAppWebView();
// Handle Authentication
}
}, onError: (err) {
// Handle exception by warning the user their action did not succeed
});
Thank you for your help!
I got the same problem after updating my project to the newest version.
Seems like the problem comes from launching the webview directly in the flutter app.
found a workaround for it:
use the launchmode option in the launchUrlString Function:
launchUrlString(_url,mode: launchMode.externalApplication)
When I upload .zip file or .docx ,it deos not work ,but when I choose .c files they work fine
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Failed to decode data using encoding 'utf-8', path = '/storage/emulated/0/New Text Document.zip'
File _file;
Future upload() async {
if (_file == null) { return; }
String path = _file.path.split("/").last;
var pdf = _file.readAsStringSync();
var url ="http://192.168.1.112/flutter/upload_file.php";
var data = { "path": path, "pdf": pdf };
var response = await http.post(url, body: data);
}
Future pickFile() async {
final myfile = await FilePicker.getFile();
setState(() {
_file = File(myfile.path);
});
}
Here is my php file I tried to use readAsBytesSync and it gave me error
<?php
include 'connection.php';
include 'register.php';
$pdf = $_POST['pdf'];
$file_name = $_POST['path'];
file_put_contents("uploads\\".$file_name, $pdf);
?>
_file.readAsStringSync()
This assumes that your file is plain text. A *.c file most likely is. Neither zip, nor doc nor pdf files are.
What you need to do is read your file as bytes:
var contents = _file.reasAsBytesSync();
Now, I don't know what your API expects to get, so I cannot really help you with how to get the bytes transferred. But this is the way to go.