get file path from url - flutter

enter image description hereI have the url and now when I click on specific url then it should navigate to next page and open the file , here but it say that no such file directory exits.
Future<File> getFileFromUrl(String url) async {
try {
var data = await http.get(url);
var bytes = data.bodyBytes;
var dir = await getApplicationDocumentsDirectory();
File file = File("${dir.path}/mypdfonline.pdf");
File urlFile = await file.writeAsBytes(bytes);
return urlFile;
} catch (e) {
throw Exception("Error opening url file");
}
}
I should get filepath

If you are trying to open an url, you need url_launcher plugin support or web view plugin support to load the URL content. But it looks like that your trying to access the file from assets, I'm thinking. If is that so, did you added your file in assets folder and adding the path inside pubspec.yaml file. Then you have to access the file using from assets.
If my answer not helpful, please elaborate your question a bit clear with some screenshot of your app, that what you are trying to achieve. Thank you.... Happy learning.

Related

How to create a Button that allow user to download a specific file Flutter

I create a flutter app and I have this one CSV file that used as a template for user. I want to provide a Button that allow user to download this CSV file, so they can use it to have CSV file that already have our template.
The problem is I don't know if the best way is to first store the file online and get the url and use it on the flutter downloader URL or keep it in the local code asset and refer to that file when user tap the download template button. Currently I'm applying the second option and it doesn't work (I don't know if this option is possible or not), the download always fail. I'm using flutter_downloader package.
How to fix this ?
Here's my code, Is something wrong with my code ?
/// Check if the file exist or not
if (await File(externalDir!.path + "/" + fileName).exists()) {
OpenFilex.open(externalDir!.path + "/" + fileName);
} else {
/// Download the file if it doesn't exist in the user's device
final String localPath = (await getApplicationDocumentsDirectory()).path;
/// Dummy file name I want use (it exist in my asset dir"
const String fileName = 'add.png';
final data = await rootBundle.load('assets/logo/add.png');
final bytes = data.buffer.asUint8List();
final File file = File('$localPath/$fileName');
await file.writeAsBytes(bytes);
/// Download the file
final taskId = await FlutterDownloader.enqueue(
url: '',
savedDir: localPath,
fileName: fileName,
showNotification: true,
openFileFromNotification: true,
);
}
To load a file from the AppBundle and then save it to the users phone, do the following:
Put the file in assets/filename.csv and declare it in your pubspec like this:
flutter:
assets:
- assets/filename.csv
Load the file in your code:
import 'package:flutter/services.dart' show ByteData, rootBundle;
(...)
var data = (await rootBundle.load('assets/filename.csv)).buffer.asInt8List();
Save the data to a file (you need the path-provider package if you want to copy the exact code):
import 'package:path_provider/path_provider.dart' as pp;
(...)
var path = (await pp.getApplicationDocumentsDirectory()).path;
var file = File('$path/filename.csv');
await file.writeAsBytes(data, flush: true);
Edit: As Stephan correctly pointed out, if you want to store the file in the downloads folder, you will find additional information about that here. Thank you Stephan!

How to open pdf file if it already exist in device in flutter?

var tempDir = await getTemporaryDirectory();
String fullPath = "${tempDir.path}/boo2.pdf'";
print('full path $fullPath');
File file = File(fullPath);
if (await file.exists() && Platform.isAndroid)
{
} else {
download2(dio, imgUrl, fullPath);
}
Above code is used to download pdf file in flutter. If file exist in device then it should directly open it. and if it is not then it should download. Now the problem is I dont know how to open exist pdf.
Most simple solution would be to use open_filex
import 'package:open_filex/open_filex.dart';
OpenFilex.open(fullPath);
this will help you : open_file: ^3.2.1
this is the link : https://pub.dev/packages/open_file
you can open pdf by using this

How can I save a file to a user specific directory flutter Desktop?

How can I allow the user to save a file to a specific folder in Flutter?
I have built a simple desktop app for Mac that returns a file from an API.
Currently, it saves the file to a caches directory.
try {
io.Directory saveDir = await getTemporaryDirectory();
String filePath = saveDir.path;
io.File returnedFile = new io.File('$filePath/$filename.xlsx');
await returnedFile.writeAsBytes(result.bodyBytes);
print(saveDir);
} catch (e) {
print(e);
}
I played around with my original code and that provided by #Pavel and managed to write my solution to saving files to a custom user-picked directory in this fashion.
The first part opens a file picker dialogue that returns a path to a directory.
The second part provides the path to the File class that then writes the file to that directory.
Hope this helps anyone trying to save files.
String? outputFile = await FilePicker.platform.saveFile(
dialogTitle: 'Save Your File to desired location',
fileName: filename);
try {
io.File returnedFile = io.File('$outputFile');
await returnedFile.writeAsBytes(responsefile.bodyBytes);
} catch (e) {}
Use https://pub.dev/packages/file_picker
String? outputFile = await FilePicker.platform.saveFile(
dialogTitle: 'Please select an output file:',
fileName: 'output-file.pdf',
);
if (outputFile == null) {
// User canceled the picker
}

Api is returning media data in response.body in Flutter

I am using api in flutter that is returning media data so how to handle this.
ScreenShot of my code
Post Man screenshot
Thanks in advance for your precious time.
Save your response to temp file or application document directory and add Image.file widget to your project to show this downloaded file. to save file you can use path_provider package.
if(response.statusCode == 200) {
var bytes = await consolidateHttpClientResponseBytes(response);
filePath = '$dir/$fileName';
file = File(filePath);
await file.writeAsBytes(bytes);
}
else
filePath = 'Error code: '+response.statusCode.toString();
}
also check this stackoverflow question and answers.

Looking for a good sample working code for downloading any file from URL in flutter. If its with native downloader then this will be very good

Looking for a good sample working code for downloading any file from URL in flutter. If its with native downloader then this will be very good. Please help me with sample of code to download any file using native downloader in flutter.
I have used few libraries but didn't turned out well.
For a mobile device, I used the http package to download a file to the applications document directory
First, create a httpClient object
static var httpClient = new HttpClient();
Then you can create a function like this to download the file:
Future<void> _downloadFile({
required String fileName,
}) async {
String url = ...;
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
String dir = (await getApplicationDocumentsDirectory())!.path;
File file = new File('$dir/$fileName'); // Note: Filename must contain the extension of the file too, like pdf, jpg etc.
await file.writeAsBytes(bytes);
}
For a flutter web application, I felt the url_launcher package was the easiest to work with.
_launchURL() async {
String url = ...;
if (await canLaunch(url)) {
await launch(url);
print('URL Launcher success');
} else {
throw Exception('Could not launch $url');
}
}
The url_launcher package code works even for a mobile device but it opens a new browser window to download the required file which is not a good user experience so I have used 2 approaches for the same problem.
Hope I have answered your query.