Flutter Web: Downloading file from URL without opening it - file

I want users to be able to download files uploaded by them. The problem is, certein files (like .pdf) are getting open in the browser, not downloaded. Is there any solution to just download a file in Flutter Web without opening it in the web browser?
Code that I'm using:
final anchor = AnchorElement(
href: url)
..setAttribute("download", fileName)
..click();

Following this answer, you can generate url from a string or from a list of int (bytes of file). Here is a short snipper that should work (from the answer above):
import 'dart:convert';
import 'dart:html' as html; // or package:universal_html/prefer_universal/html.dart
final text = 'this is the text file';
// prepare
final bytes = utf8.encode(text);
final blob = html.Blob([bytes]);
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor = html.document.createElement('a') as html.AnchorElement
..href = url
..style.display = 'none'
..download = 'some_name.txt';
html.document.body.children.add(anchor);
// download
anchor.click();
// cleanup
html.document.body.children.remove(anchor);
html.Url.revokeObjectUrl(url);
Also, universal_html package is very handy to use html on all Flutter platforms. Using dart:html in a Flutter mobile app will make compiling fail.

Related

Unable to display a PDF file in Angular app

I have a PDF file stored in a directory within the application (assets/pdf/fileName.pdf). I need to display it on a new tab on a button click from a dialog.
Here is what I have, after looking at various answers:
In *.component.ts:
openPDF() {
this.myService.fetchPDF().subscribe(
res => {
let file = new window.Blob([res], {type: 'application/pdf'});
let fileURL = window.URL.createObjectURL(file);
window.open(fileURL, '_blank');
}
);
}
In *.service.ts:
fetchPDF(): any {
const path = 'assets/pdf/fileName.pdf';
return this.httpClient.get(PathResolver.resolveStatic(path),{responseType : 'blob'});
}
I already tried using responseType : 'arraybuffer', but it didn't work out either.
Here are the threads I have looked at:
How to Display blob (.pdf) in an AngularJS app
Angular 2 download PDF from API and Display it in View
PDF Blob - Pop up window not showing content
Failed to load PDF document - Angular JS - BLOB
I am not sure why are you using httpClient. The outcome that you want could be simply achieved by the following code
In *.service.ts:
fetchPDF(): any {
const path = 'assets/pdf/fileName.pdf'
return path;
}
In *.component.ts:
openPDF() {
window.open(this.myService.fetchPDF(), '_blank');
}
You will either need to use the html embed tag (most likely also using a safe pipe), a PDF viewer (like Google PDF Viewer) or you can open the PDF in a new tab (this is the more common approach I see). It depends on your preference.

Download files from firebase storage using ReactJs

Succesfully i have made to Upload files into firebase storage, but now i want to display all files in table and to have option to download each file.I've read the documentation in firebase but it won't work.When i click the button which function is to get all files and the i want to visualize them in table which users can see:
Show file function:
showFileUrl(){
storageRef.child('UploadedFiles/').listAll().then(function(res) {
res.items.forEach(function(folderRef) {
console.log("folderRef",folderRef.toString());
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "downloadURL");
xhr.responseType = "blob";
xhr.onload = function()
{
blob = xhr.response;//xhr.response is now a blob object
console.log(blob);
}
xhr.send();
});
}).catch(function(error) {
});
}
This is log of the network which i found when debugging.What i need to do to get all data and visualize it in table and to hava a download button and when is pressed to download the file
Network log:
Storage in firebase:
Blob object of the files:
Your code gets a list of all the files, but it doesn't actually to anything to read the data for each file.
When using the Web client SDK, the only way to get the data for a file is through a download URL as shown here. So you'll need to:
Loop through all the files you get back from listAll() (you're already doing this).
Call `getDownloadURL as shown here, to get a download URL for each file.
Then use another library/function (such as fetch()/XMLHTTPRequest) to read the data for each file.
Alternatively, if your files are images, you can stuff the download URL in an img tag as the preview.

Flutter - Save file visible to the user

In a Flutter project I create a pdf document. I can save the document in the path of the app.
But the user has no access to it. Alternatively, how can I save the file to another folder where the user sees it?
import 'package:path_provider/path_provider.dart';
Future<void> savePdfDocument() async {
final PdfCreater generatedPdf = PdfCreater(document);
final List<int> generatedPdfDocument = generatedPdf.buildPdf();
final String dir = (await getApplicationDocumentsDirectory()).path;
final String path = '$dir/example.pdf';
final File file = File(path);
file.writeAsBytesSync(generatedPdfDocument);
}
Use downloads_path_provider, on android it will save the file on Downloads.
for IOS, you need to use getApplicationDocumentsDirectoryfrom path_provider and add permissions on info.plist to make the folder visible to the user:
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>UIFileSharingEnabled</key>
<true/>
This works like a charm
String documentsPath = '/storage/emulated/0/Documents/';
if (Platform.isIOS) {
Directory path = await getApplicationDocumentsDirectory();
documentsPath = path.path;
}
Also don't forgot to add this to pubspec
path_provider: 2.0.1
Also, be sure to test on a physical device, iOS emulator won't work.

How to save Base64 String to file and view it using Flutter

I need to download and view file (if possible, for Image, PDF, etc) using Flutter.
My problem is, the file that I want to download is Base64 String.
How can I achieve that using Flutter??
Following is the code snippet to decode base64 string and save it as a file on the local device. please note in terms of viewing files, image and pdf would require different libraries.
Future<String> _createFileFromString() async {
final encodedStr = "put base64 encoded string here";
Uint8List bytes = base64.decode(encodedStr);
String dir = (await getApplicationDocumentsDirectory()).path;
File file = File(
"$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ".pdf");
await file.writeAsBytes(bytes);
return file.path;
}
Google Chrome does not let open tab with Url base64 encode, like "data:application/pdf;base64,JVBERi0xLjQKJeLj..." with javascript, so you can not open url with url_launcher, but you can download file.
Here is my code:
import 'dart:html' as html;
...
Future<void> downloadFile() {
final urlString = "data:application/pdf;base64,JVBERi0xLjQKJeLj...";
html.AnchorElement anchorElement = html.AnchorElement(href:urlString);
anchorElement.download = urlString;
anchorElement.click();
}

Download xlsx file passed from nodejs to frontend angularjs

I have a JSON array of objects that is a result of a function in nodejs. I use json2xls to convert that to an excel file, and it downloads to the server (not in a public folder, and is formatted correctly in Excel).
I would like to send a response to the frontend with the json results (to display as a preview) and show a button they can click to download the xlsx file OR display the JSON results and automatically download the file.
But I can't get it, and I've tried so many things I'm going crazy.
My controller code (the part that creates the xls file):
var xls = json2xls(results,{});
var today = (new Date()).toDateString('yyyy-mm-dd');
var str = today.replace(/\s/g, '');
var fileName = "RumbleExport_"+ str +".xlsx";
var file = fs.writeFileSync(fileName,xls,'binary');
res.download('/home/ubuntu/workspace/'+file);
The frontend controller:
vm.exportData = function(day, event, division) {
console.log('Export registrations button pressed.', vm.export);
//send the search parameters to the backend to run checks
$http.post('/api/exportData', vm.export).then(function(response){
vm.results = response.data;
console.log("Results",response);
vm.exportMessage = "Found " + vm.results.length + " registrations.";
})
.catch(function(error){
vm.exportError = error.data;
});
};
The view:
//display a button to download the export file
<a target="_self" file="{{vm.results}}" download="{{vm.results}}">Download Export File</a>
Someone please put me out of my misery. All the classes I've taken and none have covered this.
I FINALLY got it! And since I searched forever trying to make something work, I'll share the answer:
On the backend:
//save the file to the public/exports folder
var file = fs.writeFileSync('./public/exports/'+fileName,xls,'binary');
//send the results to the frontend
res.json(200).json({results:results, fileName: fileName});
On the frontend, use HTML to download a link to the file:
<a href="exports/{{fileName}}" download>Save File</a>

Resources