Skip to content

Instantly share code, notes, and snippets.

@parthdave93
Created July 1, 2020 19:11
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save parthdave93/e390d94e0c2a69216f9f0ff43c6dfdc9 to your computer and use it in GitHub Desktop.
Save parthdave93/e390d94e0c2a69216f9f0ff43c6dfdc9 to your computer and use it in GitHub Desktop.
Flutter Web file pick and upload via multipart full example
//example function body
Map<String, dynamic> fields = {
"data": filedValue,
};
var request = http.MultipartRequest(
"POST", Uri.parse('url'),
);
request.files.add(
http.MultipartFile.fromBytes(
'file', file.fileBytes,
// contentType: MediaType('application', 'octet-stream'),
filename: file.file.name,
),
);
fields.forEach((k, v) => request.fields[k] = v);
request.headers.addAll(
{
r'Content-Type': 'application/json',
r'Authorization': Authorization,
},
);
var streamedResponse = await request.send();
var _result = await http.Response.fromStream(streamedResponse);
var value = yourModelOfResponse.fromJson(jsonDecode(_result.body));
return value;
import 'dart:html' as htmlfile;
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
typedef CallbackForFilePicker = Function(List<dynamic> files);
class PlatformFilePicker {
startWebFilePicker(CallbackForFilePicker pickerCallback) async {
if (kIsWeb) {
htmlfile.InputElement uploadInput = htmlfile.FileUploadInputElement();
uploadInput.click();
uploadInput.onChange.listen((e) {
// read file content as dataURL
final files = uploadInput.files;
//was just checking for single file but you can check for multiple one
if (files.length == 1) {
final htmlfile.File file = files[0];
final reader = htmlfile.FileReader();
reader.onLoadEnd.listen((e) {
//to upload file we will be needing file bytes as web does not work exactly like path thing
//and to fetch file name we will be needing file object
//so created custom class to hold both.
pickerCallback([FlutterWebFile(file, reader.result)]);
});
reader.readAsArrayBuffer(file);
}
});
} else {
File file = await FilePicker.getFile();
pickerCallback([file.path]);
}
}
getFileName(dynamic file) {
if (kIsWeb) {
return file.file.name;
} else {
return file.path.substring(file.lastIndexOf(Platform.pathSeparator) + 1);
}
}
}
class FlutterWebFile {
htmlfile.File file;
List<int> fileBytes;
FlutterWebFile(this.file, this.fileBytes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment