问题描述
使用file_picker进行本地pdf文件预览 在ios跟andriod端正常 但是在web端选取的pdf的path值为空
解决步骤
file_picker 这个库在pub上表明是支持web端的 但是实际测试确实无法拿到pdf的path路径,于是我找啊找 还是没有找到三端都支持的库 只能换思路 web端单独处理
按照之前web端文件上传的思路
获取到选择的pdf的base64
class DocumentPicker {
static Future<List<dynamic>> open(
{List<String> types, bool multiple = false}) async {
final completer = Completer<List<String>>();
html.InputElement uploadInput = html.FileUploadInputElement();
if (types != null && types.length > 0) {
String theTypes = types.join(',');
uploadInput.accept = theTypes;
}
uploadInput.multiple = multiple;
uploadInput.click();
uploadInput.addEventListener('change', (e) async {
final files = uploadInput.files;
Iterable<Future<String>> resultsFutures = files.map((file) {
final reader = html.FileReader();
reader.readAsDataUrl(file);
reader.onError.listen((error) => completer.completeError(error));
return reader.onLoad.first.then((_) => reader.result as String);
});
final results = await Future.wait(resultsFutures);
completer.complete(results);
});
html.document.body.append(uploadInput);
return completer.future;
}
}
将base64 转成 Unit8List
Future<Uint8List> _createFileFromString(base64Str) async {
final encodedStr = base64Str;
Uint8List bytes = base64.decode(encodedStr);
return bytes;
}
void _openFileExplorerWeb(context) async {
try {
DocumentPicker.open(types: ['data:content/type']).then((list) async {
String base64Str = list[0].toString().split(',')[1];
Uint8List bytes = await _createFileFromString(base64Str);
final blob = html.Blob([bytes], 'application/pdf');
final url = html.Url.createObjectUrlFromBlob(blob);
html.window.open(url, "_blank");
html.Url.revokeObjectUrl(url);
}
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
}
}
还要在web端判断一下 当前是否是web端 因为web不支持platform 所以需要用到
import 'dart:io';
import 'package:flutter/foundation.dart';
class PlatformUtils {
static bool _isWeb() {
// 通过kIsWeb变量判断是否为web环境!
return kIsWeb == true;
}
static bool _isAndroid() {
return _isWeb() ? false : Platform.isAndroid;
}
static bool _isIOS() {
return _isWeb() ? false : Platform.isIOS;
}
static bool _isMacOS() {
return _isWeb() ? false : Platform.isMacOS;
}
static bool _isWindows() {
return _isWeb() ? false : Platform.isWindows;
}
static bool _isFuchsia() {
return _isWeb() ? false : Platform.isFuchsia;
}
static bool _isLinux() {
return _isWeb() ? false : Platform.isLinux;
}
static bool get isWeb => _isWeb();
static bool get isAndroid => _isAndroid();
static bool get isIOS => _isIOS();
static bool get isMacOS => _isMacOS();
static bool get isWindows => _isWindows();
static bool get isFuchsia => _isFuchsia();
static bool get isLinux => _isLinux();
}