我想从 Flutter Web 应用程序将图像上传到服务器。有没有更好的方法来做到这一点。
我已经尝试过几个插件。image-picker, file-picker 但它们都不支持flutter web。
我想从 Flutter Web 应用程序将图像上传到服务器。有没有更好的方法来做到这一点。
我已经尝试过几个插件。image-picker, file-picker 但它们都不支持flutter web。
您可以使用 dart:html 的 FileUploadInputElement 类。
首先要做的是导入 dart:html。
import 'dart:html';
实现以下代码以启动文件选择器:
_startFilePicker() async {
InputElement uploadInput = FileUploadInputElement();
uploadInput.click();
uploadInput.onChange.listen((e) {
// read file content as dataURL
final files = uploadInput.files;
if (files.length == 1) {
final file = files[0];
final reader = new FileReader();
reader.onLoadEnd.listen((e) {
_handleResult(reader.result);
});
reader.readAsDataUrl(file);
}
});
}
目前有很多选择。有file_picker、drop_zone等等。此示例目前适用于最大为 530MB 的文件。
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
VoidCallback openFilePicker = () async {
FilePickerResult? result;
print("pick files");
result = await FilePicker.platform.pickFiles(allowMultiple: true, withReadStream: true, withData: false);
if (result != null) {
print(result.files.first.name);
//---Create http package multipart request object
var request = http.MultipartRequest(
"POST",
Uri.parse("http://127.0.0.1:8000/backend/api/upload"),
);
List<PlatformFile>? files = result.files;
if (files != null) {
print("adding files selected with file picker");
for (PlatformFile file in files) {
//-----add selected file with request
request.files.add(http.MultipartFile(
"Your parameter name on server side",
file.readStream!,
file.size,
filename: file.name));
}
}
//-------Send request
var resp = await request.send();
//------Read response
String result2 = await resp.stream.bytesToString();
//-------Your response
print(result2);
}
};
TextButton selectAndSend = TextButton(onPressed: openFilePicker, child: Text("Selet and send"));
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Flutter bug example')),
body: selectAndSend
)
);
}
}