Summary
I write a example using flutter to upload file with multipart/form-data
format with 2 steps. Both steps contains optional package for options. The example request contains 2 fields: File for {file:slide.pdf} and Text for {owner:Gary}.
Stpe 1: Pick File (to bytes data)
Method 1: Use html(built-in library, web only), or universal_html
example code:
// choose one of below pacakges
import 'dart:html' as html;
// import 'package:universal_html/html.dart' as html;
Future<html.File?> pickHtmlFile() async {
final uploadElement = html.FileUploadInputElement()
..multiple = false
..click();
await uploadElement.onChange.first;
return uploadElement.files?.first;
}
Future<Uint8List?> readBytes(html.File file) async {
final reader = html.FileReader()
..readAsArrayBuffer(file);
await reader.onLoadEnd.first;
return reader.result as Uint8List?;
}
...
final htmlFile = await pickHtmlFile();
if (htmlFile == null) return;
final bytes = await readBytes(htmlFile);
if (bytes == null) return;
// htmlFile.name => file name
// bytes => byte data of the file
...
Method 2: use file_picker (Recommand)
example code:
import 'package:file_picker/file_picker.dart';
final picked = await FilePicker.platform.pickFiles();
final platformFile = picked?.files.single;
final bytes = platformFile?.bytes;
if (platformFile == null || bytes == null) return;
// platformFile.name => file name
// bytes => byte data of the file
Step2: Upload Formdata with POST
Method1: use http (Official)
example code:
import 'package:http/http.dart' as http;
...
final multipartFile =
http.MultipartFile.fromBytes('file', bytes, filename: filename);
final request = http.MultipartRequest('POST',Uri.parse('[YOUR API URL HERE]'))
..files.add(multipartFile)
..fields['owner'] = 'Gary';
final responseStream = await request.send();
final response = await http.Response.fromStream(responseStream);
// response.statusCode => 200 is OK
// response.body => response data here
Method2: use dio
example code:
import 'package:dio/dio.dart' as dio;
...
final multipartFile = dio.MultipartFile.fromBytes(bytes, filename: filename);
final formData = dio.FormData.fromMap({'file': multipartFile, 'owner': 'Gary'});
final response = await dio.Dio().post('[YOUR API URL HERE]',data: formData,);
// response.statusCode => 200 is OK
// response.data => response data here
base64
encoded image as a string in body with content type of header equal toapplication/x-www-form-urlencoded
and it works. – Siamang