I would need some method on the server side (cloud function) to give me a 'changing' url when an image is updated with same file name. Is that possible?
Background: I use the recent firebase extension to create thumbnails. When thumbnails are generated, I store the download urls on firestore for access in my mobile app
As per difference between getSignedUrl() and getDownloadUrl() I use getSignedUrl().
But this method gives me 'same' url even when the underlying image changes. And because the url is same the Widget (I use flutter) does not re-build and the modified image is not reflected
exports.thumbnailHandler = functions.storage.object().onFinalize(async (object) => {
const contentType = object.contentType;
const filePath = object.name;
const fileBucket = object.bucket;
const fileRef = admin.storage().bucket(fileBucket).file(filePath);
const options = {
action: 'read',
expires: '12-31-2099'
};
fileRef.getSignedUrl(options).then(results => {
var downloadUrl = results[0];
console.log(downloadUrl); //This is same url everytime, even when image changes but with same file name
}
}
Is there an alternative to signedUrl above something equivalent to downloadUrl from flutter sdk?
Update This is the answer: This gives me the downloadUrl as I would from a client https://stackoverflow.com/a/53744579/11749006
Related
My Use Case:
Users in my app can create lists of items. I want the users to be able to share a link to one of their lists.
I want individuals who click the shared link to see the list of items in a web browser and not need the app installed.
Create the Dynamic Link
The first thing I need to do is create a dynamic link for a user to share. I struggled with this at first and then looked at this question here: Flutter - How to pass custom arguments in firebase dynamic links for app invite feature?
After looking at that I build my own class like so:
class PackDynamicLinkService {
Future<Uri> createDynamicLink({required String packID}) async {
final DynamicLinkParameters parameters = DynamicLinkParameters(
// This should match firebase but without the username query param
uriPrefix: 'ttps://appName.app/p',
// This can be whatever you want for the uri, https://yourapp.com/groupinvite?username=$userName
link: Uri.parse('https://appName.app/p?pack=$packID'),
androidParameters: const AndroidParameters(
packageName: 'com.test.demo',
minimumVersion: 1,
),
iosParameters: const IOSParameters(
bundleId: 'com.test.demo',
minimumVersion: '1',
appStoreId: '',
),
);
final dynamicLink = await FirebaseDynamicLinks.instance.buildShortLink(
parameters,
shortLinkType: ShortDynamicLinkType.unguessable,
);
return dynamicLink.shortUrl;
}
}
I then called that function in my app and I am able to get a URL that looks like this: https://appName.app/p?pack=lVeSBUHoLX52zPqAiB9A
So far so good. Now I just need to click the link and read the parameter $packID that I passed to it inside my web app. Then I can route them to the correct view and display the list.
Processing Dynamic Link
in my marin.dart I tried to retrieve the params with:
//get link stuff
final PendingDynamicLinkData? initialLink =
await FirebaseDynamicLinks.instance.getInitialLink();
if (initialLink != null) {
final Uri fullLink = initialLink.link;
print(fullLink.queryParameters['pack']);
}
but when I upload to firebase hosting to see if this code works for testing, I get this error:
Uncaught MissingPluginException(No implementation found for method
FirebaseDynamicLinks#getInitialLink on channel
plugins.flutter.io/firebase_dynamic_links)
After doing some more research it seems that firebase_dynamic_links package may not be available for web? So does that mean my original use case is not possible with flutter at this time?
You would want to take the link received and parse it using something like:
var PendingDynamicLinkData? initialLink =
await FirebaseDynamicLinks.instance.getInitialLink();
if (kIsWeb) {
String link = Uri.base;
initialLink = await
FirebaseDynamicLinks.instance.getDynamicLink(Uri.parse(link));
}
if (initialLink != null) {
final Uri fullLink = initialLink.link;
print(fullLink.queryParameters['pack']);
}
Here, we are checking if its a web app and then we can parse the dynamic link and get the info for it. We just check for the Uri that was used in our web app.
Is there any way to get files like .pdf downloaded directly on user's device instead of opening this pdf in the browser?
This code works for downloading non browser supported files but it opens pdf, mp3, etc. in the browser.
final anchor = AnchorElement(
href: pickedFile)
..setAttribute("download", fileName)
..click();
If someone is still searching for solution.Here is what I have done.
Anchor tag will directly download file if it has download attribute.
Note: Download attribute is only supported for same-origin request
So instead of assigning external URL link to anchor element. Create Blob object from PDF data and create Object URL from that.
var url = Url.createObjectUrlFromBlob(Blob([data]));
AnchorElement(href: url)
..setAttribute('download', '<downloaded_file_name.pdf>')
..click();
I am using Firebase to store file so here is the complete code.
FirebaseStorage.instance.ref(resumeFileName).getData().then(
(data) {
var url = Url.createObjectUrlFromBlob(Blob([data]));
AnchorElement(href: url)
..setAttribute('download', '<downloaded_file_name.pdf>')
..click();
}
);
by following the steps below, you can download the file automatically by the browser and save it in the download directory.
In this method, http and universal_html packages are used.
The important thing is to manage Multiplatform-Mode and using this code, is better you create 3 separate dart files.
switch_native_web.dart
web.dart
native.dart
/// switch_native_web.dart
import 'native.dart' if (dart.library.html) 'web.dart' as switch_value;
class SwitchNativeWeb {
static void downloadFile({required String url,
required String fileName ,required String dataType}){
switch_value.downloadFile(dataType: dataType,fileName: fileName,url: url);}
}
...
/// web.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:universal_html/html.dart' as universal_html;
Future<void> downloadFile(
{required String url,
required String fileName,
required String dataType}) async {
try {
// first we make a request to the url like you did
// in the android and ios version
final http.Response r = await http.get(
Uri.parse(url),
);
// we get the bytes from the body
final data = r.bodyBytes;
// and encode them to base64
final base64data = base64Encode(data);
// then we create and AnchorElement with the html package
final a =
universal_html.AnchorElement(href: '$dataType;base64,$base64data');
// set the name of the file we want the image to get
// downloaded to
a.download = fileName;
// and we click the AnchorElement which downloads the image
a.click();
// finally we remove the AnchorElement
a.remove();
} catch (e) {
print(e);
}
}
...
/// native.dart
Future<void> downloadFile({required String url, required String fileName,
required String dataType}) async {}
And using the following sample code for calling the downloadFile method wherever you need:
...
GestureDetector(
onTap: () => SwitchNativeWeb.downloadFile(
url: "https://... your url ..../download.jpg",
fileName: "download.jpg",
dataType: "data:image/jpeg"),
child: Text('download')
)
...
I only wrote the code related to web download (according to the question), you can write the code related to ios and android download in the native .dart file.
Use Dio Library.
dependencies:
dio: ^3.0.10
to download file
response = await dio.download("https://www.google.com/", "./xx.html");
this video will help you.
I am developing an app that fetches a custom object from my REST API. The object's class is called MyItem and it looks like this:
class MyItem {
String title;
String profilePicURL;
String videoURL;
}
As you can see, the class contains two URLs, that points to a png and mp4 files.
I would like to implement a feature, which allows the user to download the object, in order to access its content offline. I have no problem saving the title property, but how can I save the two URLs (because I don't want the URL itself to be saved, I would like to save the file it points to).
Any idea what is the best way doing that in Flutter and Dart?
Thank you!
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
var directory = await getApplicationDocumentsDirectory();
Dio dio = Dio();
//Below function will download the file you want from url and save it locally
void Download(String title, String downloadurl) async{
try{
await dio.download(downloadurl,"${directory.path}/$title.extensionoffile",
onReceiveProgress: (rec,total){
print("Rec: $rec, Total:$total");
setState(() {
//just to save completion in percentage
String progressString = ((rec/total)*100).toStringAsFixed(0)+"%";
}
);
});
}
catch(e){
//Catch your error here
}
}
Now again wherever you want just use
var directory = await getApplicationDocumentsDirectory();
String filepath = "{directory.path}/filename.fileextension";
Now you can use this Image.file('filepath'); //to display those image
also you can use
video player plugin
where again VideoPlayerController.file('filepath') //to show video but read documention properly
These are just a whole steps or a broader view, you need to use them as a map and build your code.That is have a proper file name and extension saved or correctly fetched or mapped
I am trying to use QuillJS to let the user write a rich text, and then store it as JSON to display later on. There are 2 of these rich text areas in a single form, and may include images. QuillJS encodes images as base64 strings, and my POST request results in 413 by Express.
I have tried to change the limits by adding express json parameters, even trying extreme numbers.
// app.js
//----------------------------------------------------
// Middlewares
//----------------------------------------------------
app.use(express.json({limit: '2000mb'}));
app.use(express.urlencoded({extended: true, limit:'2000mb'}));
Even this did not help and I think it is not logical to let these parameters with such values.
I tried with json and urlencoded enctypes. When I tried to post with multipart/form, req.body was empty.
// My html page (pugJS)
form(enctype='application/x-www-form-urlencoded', action='/editor/page',
method='POST', onsubmit='return addContent()')
.form-control
label Content-1
div#toolbar
div#editor
input#content(name='content', type='text', hidden)
addContent() function that runs before form submit simply changes input#content's value with JSON.stringify(#editor.getContents())
I want to be able to store two quill content in a single database row, to display later.
A better approach to this would be to overwrite the image upload function and then save the image in Amazon S3 or some cloud server. Then you paste it inside the editor as <img src="http://uploaded-image-url"> This would solve your problem of maximum memory issue.
I fixed my problem few hours before #argo mentioned and I did it that way. So I wanted to post little bit of detail to the solution. I have been also guided by a github issue but can't seem to find the link again, in case I find it I will edit the post and add it.
// Quill - EN content
var quillEn = new Quill('#editor-en', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
// set custom image handler
quillEn.getModule('toolbar').addHandler('image', () => {
selectLocalImage(quillEn);
});
// create fake input to upload image to quill
function selectLocalImage(editor) {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/png, image/jpeg')
input.click();
// Listen upload local image and save to server
input.onchange = () => {
const file = input.files[0];
saveImageToServer(editor, file);
};
}
// upload image to server
function saveImageToServer(editor, file) {
const fd = new FormData();
fd.append('image', file);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/page/upload_image', true);
xhr.onload = () => {
if (xhr.status === 200) {
// this is callback data: url
const url = JSON.parse(xhr.responseText).data;
insertToEditor(editor, url);
}
};
xhr.send(fd);
}
// manipulate quill to replace b64 image with uploaded image
function insertToEditor(editor, url) {
// push image url to rich editor.
const range = editor.getSelection();
editor.insertEmbed(range.index, 'image', url.toString());
}
In the backend where you POST image, you must return json as { data: FullUrlToImg } with 200 response, if you want to change your status to 201 or something else, don't forget to update it in saveImageToServer function.
So to summarize, you set custom image handler for your quill editor, you post the image to server as soon as user chooses to insert, then you replace the URL with your uploaded image in the editor.
Thanks.
I have small bug in my program.
I have firebase Storage in my app. I wanna let the user to upload image to the storage.
the thing is when the user uploads image and then tries to upload another image. what the program does it overwrites the image was uploaded before.
what I want is to avoid "overwrite" when the user wants to upload another image. and keep both images in different file
let currentUser = Auth.auth().currentUser
let StorageRefrenece = Storage.storage().reference()
let posterImageRef =
StorageRefrenece.child("posters").child(currentUser!.uid).child("posterOne.jpg")
Thnx
That is happening because you're storing them with the same name. In Firebase Storage you're the one in charge to decide the name of the files, there is no ".childByAutoId()".
If you want to have different files, you can create random values to name them, that is well explained here: How does one generate a random number in Apple's Swift language?
Your final code should look like this:
StorageRefrenece.child("posters").child(currentUser!.uid).child(<#Any Random Value#>)
import { v4 as uuid } from "uuid";
const unId = uuid();
const handleSubmit = async () => {
const imageRef = ref(storage, unId);
uploadBytes(imageRef, image)
.then(() => {
getDownloadURL(imageRef)
.then((url) => {
console.log("Url received from firebase: ",url)
setUrl(url);
})
})
}