Dio sends empty form body in POST request
I am sending the following POST request to my node.js server:
import 'package:dio/dio.dart';
import 'dart:io';
print("--- userData: $userData"); // its a Map<String, dynamic>
Dio dio = new Dio();
dio.options.headers = {
'Authorization': 'Bearer ' + prefs.getString("TOKEN"),
'uuid': _uuid
};
dio.options.contentType = ContentType.parse("application/json");
FormData formData = new FormData.from(userData);
print("--- updated user info: $formData");
Response response = await dio.post("https://myapi.com/api/user/update", data: formData);
if(response.statusCode == 200) {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("User Info Updated"),
));
} else {
Map<String, dynamic> _responseMap = json.decode(response.data);
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text(_responseMap['message']),
));
}
where the userData and formData print statement prints out something like this:
{
first_name: John,
last_name: Doe,
age: 56,
gender: Male,
phone: 8888888888,
email: [email protected],
others: some text and some other stuff
}
However on my server side I get an empty body. However when I do the same thing with Flutter's http:
Map<String, String> headersMap = {
'Content-Type' : 'application/json',
'Authorization' : 'Bearer ' + prefs.getString("TOKEN"),
'uuid': _uuid
};
http.post(
'https://myapi.com/api/user/update',
body: json.encode(userData),
headers: headersMap
).then((http.Response response){
if(response.statusCode == 200) {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("User Info Updated"),
));
}
});
I receive the data on server side.
I even tried the Dio code by commenting the dio.options.contentType line but I still get empty request body. What is going on? What am I missing?
you should send post request directly as follows:
Response response = await dio.post("https://myapi.com/api/user/update", data: userData);
In your situation, you shouldn't use FormData,because using FormData will lead the dio to set request contentType as "multipart/form-data"。
Thanks, it worked.
you should send post request directly as follows:
Response response = await dio.post("https://myapi.com/api/user/update", data: userData);In your situation, you shouldn't use
FormData,because usingFormDatawill lead the dio to set requestcontentTypeas "multipart/form-data"。
But what about the case of sending file to the server using post request
you should send post request directly as follows:
Response response = await dio.post("https://myapi.com/api/user/update", data: userData);In your situation, you shouldn't use
FormData,because usingFormDatawill lead the dio to set requestcontentTypeas "multipart/form-data"。But what about the case of sending file to the server using post request
u can use FormData but don't specify a content type if u specified a content type the body will be empty I tried it and it worked that way
hi guys, i face this issue, i have tried the ways above but none of them can resolve my issue
this is my setup and data
-
Dio ` static final option = BaseOptions( baseUrl: AppConfig.instance.baseUrl, connectTimeout: 50000, receiveTimeout: 50000);
static final interceptor = PrettyDioLogger( requestHeader: true, requestBody: true, responseBody: true, responseHeader: false, error: true, compact: true, maxWidth: 90);
final Dio dio = Dio(option) ..interceptors.add(interceptor);`
-
method send
Future<Response> postFileDigital( FormData formFileDigital, String token) async { dio.options.headers['authorization'] = "Bearer " + token; return await dio.post(FILE_DIGITAL_UPLOAD_URL, data: formFileDigital); } -
this is form
FormData.fromMap(<String, dynamic>{ "attendance_date": currentDates.first, "check_in": currentDates[1].substring(0, 8), "lat": geoLocation.latitude.toString(), "lng": geoLocation.longitude.toString(), "status_health": "HEALTHY", // "photo": await MultipartFile.fromFile(file.path) }i have been log the request data is exist when sending data to server but the server read empty data. anyone can help me ?
my dio version => dio: ^3.0.9
O well done for response
On Tue, Feb 2, 2021, 10:51 AM M Izzuddin A Q [email protected] wrote:
hi guys, i face this issue, i have tried the ways above but none of them can resolve my issue
this is my setup and data
Dio ` static final option = BaseOptions( baseUrl: AppConfig.instance.baseUrl, connectTimeout: 50000, receiveTimeout: 50000);
static final interceptor = PrettyDioLogger( requestHeader: true, requestBody: true, responseBody: true, responseHeader: false, error: true, compact: true, maxWidth: 90);
final Dio dio = Dio(option) ..interceptors.add(interceptor);`
method send Future
postFileDigital( FormData formFileDigital, String token) async { dio.options.headers['authorization'] = "Bearer " + token; return await dio.post(FILE_DIGITAL_UPLOAD_URL, data: formFileDigital); } this is form FormData.fromMap(<String, dynamic>{ "attendance_date": currentDates.first, "check_in": currentDates[1].substring(0, 8), "lat": geoLocation.latitude.toString(), "lng": geoLocation.longitude.toString(), "status_health": "HEALTHY", // "photo": await MultipartFile.fromFile(file.path) }
i have been log the request data is exist when sending data to server but the server read empty data. anyone can help me ?
my dio version => dio: ^3.0.9
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/flutterchina/dio/issues/88#issuecomment-771382339, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQUGBBBDX4FQUF2KSW6CEDDS46HE3ANCNFSM4GAILCGQ .
Hi, i face this issue, @Izudinalqasam did you solve it?
Are you here
On Fri, Feb 12, 2021, 1:07 AM mayma93 [email protected] wrote:
Hi, i face this issue, @Izudinalqasam https://github.com/Izudinalqasam did you solve it?
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/flutterchina/dio/issues/88#issuecomment-777756507, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQUGBBC3D7BSNF5U7L6MKM3S6Q2HVANCNFSM4GAILCGQ .
Please explain issue
On Fri, Feb 12, 2021, 2:41 AM mayma93 [email protected] wrote:
yes
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/flutterchina/dio/issues/88#issuecomment-777810233, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQUGBBEN7RE6FTE6VXKLEY3S6RFGZANCNFSM4GAILCGQ .
i am trying to upload images using dio FormData, the request body containing two parts:
-images: array of images
-element: element information (json)
when i log my FormData the data exist, but it seems the server is recieving an empty data..
i got 400 (bad request) with message : required request part 'element' is not present
@mayma93 not yet, for that case i use alternative http package and it work fine coexisting with dio
@Izudinalqasam can you share your code please? with http package
Sure! if you face any problem then let me know
static Future addProduct(
{AddProductBlock provider, List
for (Asset asset in images) {
final String _fileName = asset.name;
ByteData byteData = await asset.getByteData();
List
FormData formData = FormData.fromMap({ 'name': '${provider.pNameCon.text}', 'image': imageList, 'description': '${provider.disCon.text}', 'status': '${provider.publishstatus == true ? 0 : 1}', 'tags': provider.listofTags, 'use_variants': '${provider.useVariant}', 'variants': jsonEncode(provider.listOfVariantforUploading), 'Product_type': '${provider.producttype == true ? 0 : 1}', 'category': '${provider.furtherdetailids[0]}', 'subcategory': '${provider.furtherdetailids[1]}', 'brand': '${provider.furtherdetailids[2]}', 'units': '${provider.furtherdetailids[3]}', });
try { var responce = await Dio().post('$baseUrl$addproduct', data: formData, options: Options( headers: headerforApi, responseType: ResponseType.json, contentType: "application/json", followRedirects: false, validateStatus: (status) { return status <= 500; })); var data = responce.data; provider.setisloading(false); if (responce.statusCode == 201) { Navigator.of(provider.scaffoldKey.currentContext).pop(); Navigator.of(provider.scaffoldKey.currentContext).pop(); Navigator.push( provider.scaffoldKey.currentContext, MaterialPageRoute( builder: (c) => ChangeNotifierProvider( create: (_) => DrawerBlock(), child: RetailerDrawerPage()))); } print('add product data is = $data'); print('add product responce = ${responce.statusCode}'); } catch (e) {} }
On Fri, Feb 12, 2021 at 11:50 AM mayma93 [email protected] wrote:
can you share your code please?
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/flutterchina/dio/issues/88#issuecomment-778013364, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQUGBBAGZUWTUGBFY3YFB7DS6TFSJANCNFSM4GAILCGQ .
it's a multi-part image uploading
On Fri, Feb 12, 2021 at 11:58 AM RAO SAQIB [email protected] wrote:
Sure! if you face any problem then let me know
static Future addProduct( {AddProductBlock provider, List
images}) async { List imageList = new List (); for (Asset asset in images) { final String _fileName = asset.name; ByteData byteData = await asset.getByteData(); List
imageData = byteData.buffer.asUint8List(); MultipartFile multipartFile = new MultipartFile.fromBytes( imageData, filename: _fileName, contentType: MediaType("image", "jpg"), ); imageList.add(multipartFile); } print('name ${provider.pNameCon.text}'); print('status ${provider.publishstatus}'); print('tags ${provider.listofTags}'); print('discription ${provider.disCon.text}'); print('variants ${provider.listOfVariantforUploading}'); print('fetured ${provider.listTimes}'); print('Categories ${provider.furtherdetailids[0]}'); print('SubCategories ${provider.furtherdetailids[1]}'); print('Brand ${provider.furtherdetailids[2]}'); print('Unit ${provider.furtherdetailids[3]}'); print('product type ${provider.producttype}'); print('list of images $imageList}'); FormData formData = FormData.fromMap({ 'name': '${provider.pNameCon.text}', 'image': imageList, 'description': '${provider.disCon.text}', 'status': '${provider.publishstatus == true ? 0 : 1}', 'tags': provider.listofTags, 'use_variants': '${provider.useVariant}', 'variants': jsonEncode(provider.listOfVariantforUploading), 'Product_type': '${provider.producttype == true ? 0 : 1}', 'category': '${provider.furtherdetailids[0]}', 'subcategory': '${provider.furtherdetailids[1]}', 'brand': '${provider.furtherdetailids[2]}', 'units': '${provider.furtherdetailids[3]}', });
try { var responce = await Dio().post('$baseUrl$addproduct', data: formData, options: Options( headers: headerforApi, responseType: ResponseType.json, contentType: "application/json", followRedirects: false, validateStatus: (status) { return status <= 500; })); var data = responce.data; provider.setisloading(false); if (responce.statusCode == 201) { Navigator.of(provider.scaffoldKey.currentContext).pop(); Navigator.of(provider.scaffoldKey.currentContext).pop(); Navigator.push( provider.scaffoldKey.currentContext, MaterialPageRoute( builder: (c) => ChangeNotifierProvider( create: (_) => DrawerBlock(), child: RetailerDrawerPage()))); } print('add product data is = $data'); print('add product responce = ${responce.statusCode}'); } catch (e) {} }
On Fri, Feb 12, 2021 at 11:50 AM mayma93 [email protected] wrote:
can you share your code please?
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/flutterchina/dio/issues/88#issuecomment-778013364, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQUGBBAGZUWTUGBFY3YFB7DS6TFSJANCNFSM4GAILCGQ .
also changing values in Dio package like this
String encodeMap(data, DioEncodeHandler handler, {bool encode = true}) { var urlData = StringBuffer(''); var first = true; var leftBracket = encode ? '%5B' : '['; var rightBracket = encode ? '%5D' : ']'; var encodeComponent = encode ? Uri.encodeQueryComponent : (e) => e; void urlEncode(dynamic sub, String path) { if (sub is List) { for (var i = 0; i < sub.length; i++) { urlEncode(sub[i], '$path${(sub[i] is Map || sub[i] is List) ? i : ''}'); } } else if (sub is Map) { sub.forEach((k, v) { if (path == '') { urlEncode(v, '${encodeComponent(k)}'); } else { urlEncode(v, '$path$leftBracket${encodeComponent(k)}$rightBracket'); } }); } else { var str = handler(path, sub); var isNotEmpty = str != null && str.trim().isNotEmpty; if (!first && isNotEmpty) { urlData.write('&'); } first = false; if (isNotEmpty) { urlData.write(str); } } }
urlEncode(data, ''); return urlData.toString(); }
On Fri, Feb 12, 2021 at 11:59 AM RAO SAQIB [email protected] wrote:
it's a multi-part image uploading
On Fri, Feb 12, 2021 at 11:58 AM RAO SAQIB [email protected] wrote:
Sure! if you face any problem then let me know
static Future addProduct( {AddProductBlock provider, List
images}) async { List imageList = new List (); for (Asset asset in images) { final String _fileName = asset.name; ByteData byteData = await asset.getByteData(); List
imageData = byteData.buffer.asUint8List(); MultipartFile multipartFile = new MultipartFile.fromBytes( imageData, filename: _fileName, contentType: MediaType("image", "jpg"), ); imageList.add(multipartFile); } print('name ${provider.pNameCon.text}'); print('status ${provider.publishstatus}'); print('tags ${provider.listofTags}'); print('discription ${provider.disCon.text}'); print('variants ${provider.listOfVariantforUploading}'); print('fetured ${provider.listTimes}'); print('Categories ${provider.furtherdetailids[0]}'); print('SubCategories ${provider.furtherdetailids[1]}'); print('Brand ${provider.furtherdetailids[2]}'); print('Unit ${provider.furtherdetailids[3]}'); print('product type ${provider.producttype}'); print('list of images $imageList}'); FormData formData = FormData.fromMap({ 'name': '${provider.pNameCon.text}', 'image': imageList, 'description': '${provider.disCon.text}', 'status': '${provider.publishstatus == true ? 0 : 1}', 'tags': provider.listofTags, 'use_variants': '${provider.useVariant}', 'variants': jsonEncode(provider.listOfVariantforUploading), 'Product_type': '${provider.producttype == true ? 0 : 1}', 'category': '${provider.furtherdetailids[0]}', 'subcategory': '${provider.furtherdetailids[1]}', 'brand': '${provider.furtherdetailids[2]}', 'units': '${provider.furtherdetailids[3]}', });
try { var responce = await Dio().post('$baseUrl$addproduct', data: formData, options: Options( headers: headerforApi, responseType: ResponseType.json, contentType: "application/json", followRedirects: false, validateStatus: (status) { return status <= 500; })); var data = responce.data; provider.setisloading(false); if (responce.statusCode == 201) { Navigator.of(provider.scaffoldKey.currentContext).pop(); Navigator.of(provider.scaffoldKey.currentContext).pop(); Navigator.push( provider.scaffoldKey.currentContext, MaterialPageRoute( builder: (c) => ChangeNotifierProvider( create: (_) => DrawerBlock(), child: RetailerDrawerPage()))); } print('add product data is = $data'); print('add product responce = ${responce.statusCode}'); } catch (e) {} }
On Fri, Feb 12, 2021 at 11:50 AM mayma93 [email protected] wrote:
can you share your code please?
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/flutterchina/dio/issues/88#issuecomment-778013364, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQUGBBAGZUWTUGBFY3YFB7DS6TFSJANCNFSM4GAILCGQ .
i used MultipartFile.fromFile and i got Unsupported Media Type.. he use the default content type application/octet-stream
I think your files is not right . Please send me responce
On Fri, Feb 12, 2021, 12:14 PM lalaviiie [email protected] wrote:
i used MultipartFile.fromFile and i got Unsupported Media Type.. he use the default content type application/octet-stream
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/flutterchina/dio/issues/88#issuecomment-778023187, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQUGBBHT2UXM772ZTKUKGSLS6TIOTANCNFSM4GAILCGQ .
Please send me api output
On Fri, Feb 12, 2021, 12:14 PM lalaviiie [email protected] wrote:
i used MultipartFile.fromFile and i got Unsupported Media Type.. he use the default content type application/octet-stream
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/flutterchina/dio/issues/88#issuecomment-778023187, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQUGBBHT2UXM772ZTKUKGSLS6TIOTANCNFSM4GAILCGQ .
In case of multi part image's
On Thu, Oct 8, 2020, 2:52 PM Toykam [email protected] wrote:
But what about the case of sending file to the server using post request
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/flutterchina/dio/issues/88#issuecomment-705461518, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQUGBBH3ANPR6OHBBOW4FD3SJWDUXANCNFSM4GAILCGQ .
Future createElement(element element, List images) async { FormData formData = FormData();
if (images != null) {
for (File item in images)
formData.files.addAll([
MapEntry(
"images",
await MultipartFile.fromFile(item.path,
filename: item.path.split('/').last)),
]);
}
formData.fields.add(MapEntry("element", element.toString()));
final response = await _dio.post('/api/element/', data: formData);
}
the output: 415 {"timestamp":1613122248141,"status":415,"error":"Unsupported Media Type","message":"Content type 'application/octet-stream' not supported","path":"/api/element/"}