skip to Main Content

I get an audiofile from an API call, and I want to upload this file to my Firebase storage. The API calls returns:

{"success": true, "path": "https://developer.wontgivetheexactpath.mp3"}

When I click on the path, it automatically downloads the audio in my computer, but I don’t want that. I want it to go directly in my Storage. I tried this:

 var audioFile = createAudio(
    text: 'What is love? I don't know, but it doesn't matter.');
final ref = FirebaseStorage.instance.ref().child("audio/$audioFile");
ref.putFile(File(audioFile.toString()));

Note that createAudio() is the function that returns the path resulting from the API call.

2

Answers


  1. Chosen as BEST ANSWER

    I found it out. I had to use the package dio to download the file on my computer first, then delete it. here is the code:

    import 'dart:io';
    import 'package:dio/dio.dart';
    import 'package:path_provider/path_provider.dart';
    
    Future<File> downloadFile(String url, String fileName) async {
      Dio dio = Dio();
      final directory = await getTemporaryDirectory();
      final filePath = '${directory.path}/$fileName.mp3';
      await dio.download(url, filePath);
      return File(filePath);
    }
    

    Then I upload to Firebase Storage and delete it:

         Future<void> uploadAudioToFirebase() async {
          final audioPath = await createAudio(text: 'What is love? I don't know, but it doesn't matter.');
        
          if (audioPath['success']) {
            final String url = audioPath['path'];
            final fileName = url.split('/').last;  // Extract the file name from the URL
            final localFile = await downloadFile(url, fileName);
        
            final ref = FirebaseStorage.instance.ref().child("audio/$fileName");
            await ref.putFile(localFile);
    
        // Optionally, delete the local file after upload
            await localFile.delete();
      } else {
        print('Failed to get audio path from API.');
      }
    }
    

  2. It really won’t forward it this way, for flutter it may vary according to the OS, you will need to use the packge path to standardize the OS paths, save in a temporary path and with this temporary path you will be able to change the folder and do the navigation you want, yes I know it’s annoying but it’s a solution that I already implemented years ago and it worked

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search