需要使用universal_html插件
universal_html:
universal_html是用来替代dart:html的,使用dart:html会有如下警告:
Avoid using web-only libraries outside Flutter web plugin packages.
这是为了避免在Flutter Web插件包之外使用纯web库
导入:
import 'package:universal_html/html.dart' as html;
选择文件并上传:
Future<void> pickFile() async {
html.FileUploadInputElement uploadInput = html.FileUploadInputElement();
uploadInput.multiple = false; // 是否允许选择多文件
uploadInput.draggable = true;
uploadInput.click();
uploadInput.onChange.listen((event) {
// 选择完成
html.File? file = uploadInput.files?.first;
print('文件大小:${file?.size}');
if (file != null) {
html.FormData formData = html.FormData();
formData.appendBlob('file', file.slice(), file.name);
// 上传文件到服务器
var request = html.HttpRequest();
request.open('POST', KAPI_RootUrl + KAPI_UploadFile);
request.send(formData);
request.onLoadEnd.listen((event) {
print('上传结果:${request.responseText}');
});
}
});
}