Home > Enterprise >  How to save video to phone gallery - Dio/Flutter
How to save video to phone gallery - Dio/Flutter

Time:07-18

I'm trying to save the video in the phone gallery (downloaded using dio package) To get the path, I'm using path provider package but unable to save it in the phone gallery

Here is my code

void downloadVideo() async {

  var dir = await getExternalStorageDirectory();

                      final dio = Dio();

                      dio.download(
                          'video_url',
                          '${dir!.path}/video.mp4', // saving path, I'm trying to save it in phone gallery
                          onReceiveProgress: (actualBytes, totalBytes){
                            var percentage = actualBytes/totalBytes*100;

                    
                          }
                      );
}

Note:- I'm aware of gallery_saver package but I need to achieve this using dio and path provider

CodePudding user response:

So you already have the saving directory. You can use plugins like image_gallery_saver and gallery_saver to save your downloaded video to the gallery.

If you use image_gallery_saver, the saving code would be similar to this:

await ImageGallerySaver.saveFile(finalVideoPath);

And don't forget to delete the video in the download path after saving the video successfully to the gallery.

Final code:

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

Future<void> downloadVideo() async {
  final appDocDirectory = await getAppDocDirectory();

  final finalVideoPath = join(
    appDocDirectory.path,
    'Video-${DateTime.now().millisecondsSinceEpoch}.mp4',
  );

  final dio = Dio();

  await dio.download(
    'video_url',
    finalVideoPath,
    onReceiveProgress: (actualBytes, totalBytes) {
      final percentage = actualBytes / totalBytes * 100;
    },
  );

  await saveDownloadedVideoToGallery(videoPath: finalVideoPath);
  await removeDownloadedVideo(videoPath: finalVideoPath);
}

Future<Directory> getAppDocDirectory() async {
  if (Platform.isIOS) {
    return getApplicationDocumentsDirectory();
  }

  return (await getExternalStorageDirectory())!;
}

Future<void> saveDownloadedVideoToGallery({required String videoPath}) async {
  await ImageGallerySaver.saveFile(videoPath);
}

Future<void> removeDownloadedVideo({required String videoPath}) async {
  try {
    Directory(videoPath).deleteSync(recursive: true);
  } catch (error) {
    debugPrint('$error');
  }
}
  • Related