1. 程式人生 > 實用技巧 >flutter 圖片視訊選擇元件 image_picker

flutter 圖片視訊選擇元件 image_picker

安裝

image_picker: ^0.6.7+15

使用方法:

import 'package:image_picker/image_picker.dart';

final ImagePicker _picker = ImagePicker();

PickedFile pcikeFile;
// 圖片
pcikeFile = await _picker.getImage(source: ImageSource.gallery);
pcikeFile = await _picker.getImage(source: ImageSource.camera);

// 視訊
pcikeFile = await
_picker.getVideo(source: ImageSource.gallery, maxDuration: const Duration(seconds: 60)); pcikeFile = await _picker.getVideo(source: ImageSource.camera, maxDuration: const Duration(seconds: 60));
PickedFile 轉 檔案物件 file
import 'dart:io';

File file = File(pcikeFile.path)

在android 下,選擇相簿視訊時有個bug, 得到的路徑中檔名時xxx.jpg

如圖,我選擇一個相簿中視訊得到pcikeFile.path路徑如下 ,

暫時解決辦法:

先判斷 android 環境 然後判斷是否相簿選擇的視訊,然後 修改 檔名字的字尾為 .mp4,就可以正常上傳,正常使用了

var path = pcikeFile.path;
String suffix = path.substring(path.lastIndexOf(".") + 1, path.length);
if (Platform.isAndroid && imageSource == ImageSource.gallery && type == 'video
') { suffix = 'mp4'; } int num = new DateTime.now().millisecondsSinceEpoch; String name = num.toString() + '.' + suffix; // 如下,這樣把這個Map 按檔案上傳方式上傳即可 Map item = {'path': path, 'name': name,};

親測可用