I am not able to upload images and form data to rest api using DIO package in flutter - flutter

I am not able to upload image to rest api in flutter I have checked the api its working fine.
I am not able to convert the file (image) to a uploadable form, can any one help me with that?
I have run flutter doctor -v everything is fine :)
Here is the code I am using to post form data:
Future<void> uploadAccountDetails(AccountDetailsModel details) async {
var url = baseUrl + '/api/uploads/images';
try {
Dio dio = new Dio();
FormData formData = new FormData.fromMap(
{
'city': details.cityName,
'country': details.countryName,
'residence_address': details.address,
'dob': details.dob,
'id_num': details.id,
'passport_num': details.passportNo,
'driving_license_nim': details.drivingLicNo,
'user_id': 162,
'postal_code': details.postalCode,
'id_pic': await MultipartFile.fromFile(details.idPic.path,
filename: basename(details.idPic.path)),
'driving_license_pic':
await MultipartFile.fromFile(details.drivingLicPic.path,
filename: basename(
details.drivingLicPic.path,
)),
'birth_certificate': await MultipartFile.fromFile(
details.drivingLicPic.path,
filename: basename(details.birthCertPic.path),
),
'residence_permit_pic': await MultipartFile.fromFile(
details.resPermitPic.path,
filename: basename(details.resPermitPic.path),
),
'profile_pic': await MultipartFile.fromFile(details.profilePic.path,
filename: basename(details.profilePic.path)),
},
);
print(formData);
Response response = await dio.post(
url,
data: formData,
onSendProgress: (received, total) {
if (total != -1) {
print((received / total * 100).toStringAsFixed(0) + "%");
}
},
);
print(response.statusCode);
// print(response);
} catch (e) {
print(e);
throw (e);
}
}
The logs of error are as follows:
I/flutter (22523): DioError [DioErrorType.RESPONSE]: Http status error
[500] I/flutter (22523): DioError [DioErrorType.RESPONSE]: Http status
error [500]
The status error is:
I/flutter (22523): DioError [DioErrorType.RESPONSE]: Http status error
[500]
I searched this error but didnt find any solution, can anyone help me with that?

I used dio for post a file path with some other information in this way:
Dio dio = new Dio();
FormData formData = new FormData();
formData.add(
"apiKey",
"my_api_key",
);
formData.add(
"file",
"image_path",
);
Response response = await dio.post(
"https://localhost",
data: formData,
onSendProgress: (int sent, int total) {
// do something
},
).catchError((onError) {
throw Exception('something');
});

Related

flutter error 415 when uploading image to the server

I want to upload an image to the server, I put all settings in the request but every time i get this error
I/flutter (17478): file response code 415
I/flutter (17478): file response body {code: 0441901, message: Non supported file type application/octet-stream only support this types[ image/jpeg,image/png ]., args: {}}
the code I'm using
import 'package:dio/dio.dart' as d;
void uploadPhoto({required XFile? image}) async {
final file = File(image!.path);
final mimeType = lookupMimeType(file.path);
print('image size: ${file.lengthSync()}');
print('image type: $mimeType');
d.FormData formData =
d.FormData.fromMap({
"avatar": await d.MultipartFile.fromFile(file.path, filename: image.name)});
d.Response response =
await d.Dio().patch('$baseURL/user/file',
data: formData,
options: d.Options(
validateStatus: (_) => true,
contentType: 'multipart/form-data',
headers: <String, dynamic>{
'Authorization': 'Bearer $accessToken',
}
)
);
print('file response code ${response.statusCode}');
print('file response body ${response.data}');
}
I have tried too many things but non of them worked for me and here's one of them
[https://stackoverflow.com/questions/64176638/how-to-upload-image-to-server-with-flutter][1]

How can I use flutter uploader and chunk uploader on the same request

I am searching for a way to upload a chunked image in a background task in flutter for Android. I already took a look at flutter_uploader and chunked_uploader plugins but it don't seems they are compatible.
Here is the documentation for the API I am trying to upload to:
piwigo upload async endpoint
Right now I am using a non chunked request with Dio to another endpoint:
void uploadPhotos(List<Asset> photos) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
Map<String, String> queries = {"format":"json", "method": "pwg.images.upload"};
photos.forEach((element) async {
ByteData byteData = await element.getByteData();
List<int> imageData = byteData.buffer.asUint8List();
FormData formData = FormData.fromMap({
"category": widget.category,
"pwg_token": prefs.getString("pwg_token"),
"file": MultipartFile.fromBytes(
imageData,
filename: element.name,
),
"name": element.name,
});
Response response = await API.dio.post("ws.php",
data: formData,
queryParameters: queries,
);
if (response.statusCode == 200) {
print(response.data);
if(json.decode(response.data)["stat"] == "ok") {
SnackBar snackBar = SnackBar(
content: Text("Successfully uploaded ${element.name}"),
duration: Duration(seconds: 2),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
} else {
print("Request failed: ${response.statusCode}");
}
);
}
So, is there a way to use the two plugins for a single request and if not, what should I use to fulfill my needs ?

Flutter Dio interceptor: DioError [DioErrorType.DEFAULT]: Bad state: Can‘t finalize a finalized MultipartFile

Hi i'm trying refreshtoken logic in Dio interceptor. it's working fine for json body params, but its throwing DioError [DioErrorType.DEFAULT]: Bad state: Can‘t finalize a finalized MultipartFile when i tried uploading images.
onError: (DioError error) async {
// Do something with response error
if (error.response?.statusCode == 401) {
// _dio.interceptors.requestLock.lock();
Response response;
RequestOptions options = error.response.request;
response = await _dio
.post('/user/refresh', data: {"refreshToken": _refreshToken});
if (response.statusCode == 200) {
final userData = json.encode(
{
'token': response.data["accessToken"],
'tokenType': _tokenType,
'refreshToken': response.data["refreshToken"]
},
);
prefs.setString('userData', userData);
options.data = formData;
}
options.headers["Authorization"] =
"$_tokenType ${response.data['accessToken']}";
return await _dio.request(options.path, options: options);
} else {
throw error;
}
I put together a workaround for this issue which basically consists of rebuilding the FormData before retrying. It feels a bit hacky but it works. I start by passing any info I need for the reconstruction in via the "extra" map in the request options so the interceptor has access to it. Here is some pseudo code:
//original request
dioResponse = await dio.post(
'http://my/api/endpoint',
data: myOriginalFormData,
options: Options(
headers: myHeaders,
extra: {'pathToMyFile': pathToMyFile},
),
);
//and in my interceptor I use it to construct a fresh FormData that has not been finalized
final FormData newFormData = FormData.fromMap({
'file': await MultipartFile.fromFile(
requestOptions.extra['pathToMyFile'],
contentType: MediaType('application/json', 'json')),
});
//retry with the fresh FormData
return dio.request(
requestOptions.path,
data: newFormData,
options: requestOptions,
cancelToken: requestOptions.cancelToken,
onReceiveProgress: requestOptions.onReceiveProgress,
onSendProgress: requestOptions.onSendProgress,
queryParameters: requestOptions.queryParameters,
);
Anyone have thoughts on this approach? Any major downsides?

Why Dio with Flutter does not post file with values using json header

I am new to Flutter
I am trying to pass data in json format and file on same request using dio framework. code I'm using is below, anything wrong I'm doing?
return FormData.fromMap({
'value1' : value.value1(),
'value2' : value.value2(),
"attachments": [
await MultipartFile.fromFile(fileImage.path,
filename: "storeName.jpeg")
]
});
}
static Future<bool> createStore(File fileImage, StoreDetails store) async{
bool isDone = false;
var dio = Dio();
dio.options.baseUrl = UrlHelper.BASE_CORE_URL;
dio.options.headers['Authorization'] = 'Bearer '+ token;
dio.options.headers['Content-Type'] = 'application/json';
Response response;
try{
response = await dio.post(
'Url',
data: await formData(fileImage, values),
onSendProgress: (received, total) {
if (total != -1) {
print((received / total * 100).toStringAsFixed(0) + "%");
}
},
);
print(response.data);
return true;
}catch(e){
print(e.toString());
return true;
}
}
How I post data on postman
And I get this error DioError [DioErrorType.RESPONSE]: Http status error [415]
I am able to post image and json object from postman successfully.

Erro 502 with dio [duplicate]

This question already has answers here:
How to upload images to server in Flutter?
(15 answers)
Closed 3 years ago.
How to make upload the image with dio in flutter?
void _postHttp() async {
try {
Dio dio = Dio();
dio.options.contentType = Headers.formUrlEncodedContentType;
FormData formData = new FormData.fromMap({
"file": await MultipartFile.fromFile("/Users/rogerio/Downloads/tshirt_view_kovi.jpg",
filename: "tshirt_view_kovi.jpg"),
"type": "checklist",
"source": "0bef60ed-f538-4a35-b5ef-70f7dfaf510e"
});
Response response = await dio.post(
"https://api.kovi.dev/docs/upload-generic",
data: formData,
options: Options(contentType: Headers.jsonContentType));
print(response);
} catch (e) {
print(e);
}
}
My code return error 502
Why do you set contentType to json? it should be multipart: multipart/form-data. Try this snippet without any options:
final dio = Dio();
final formData = FormData.fromMap({
"file": await MultipartFile.fromFile(
"/Users/rogerio/Downloads/tshirt_view_kovi.jpg",
filename: "tshirt_view_kovi.jpg",
),
"type": "checklist",
"source": "0bef60ed-f538-4a35-b5ef-70f7dfaf510e"
});
final response = await dio.post(
"https://api.kovi.dev/docs/upload-generic",
data: formData
);