I want to upload image to the server from flutter web application. Is there any better way of doing that.
I've already tried with couple of plugins. image-picker, file-picker But none of them are supported for flutter web.
I want to upload image to the server from flutter web application. Is there any better way of doing that.
I've already tried with couple of plugins. image-picker, file-picker But none of them are supported for flutter web.
you can use the FileUploadInputElement class of dart:html.
The first thing to do is to import dart:html.
import 'dart:html';
Implement following code to start a file picker:
_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);
}
});
}
There are plenty options at the moment. There is file_picker, drop_zone and so one. This example works at the moment for files up to the size of 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
)
);
}
}