how to send Uint8List data in Dio flutter - flutter

I want to send the Uint8List in the flutter dio, but I am getting this error : "Stream type must be Stream<List>, but _MultiStream is found."
Future<void> uploadImageUrl() async {
Options options = Options(headers: {
'Accept': "*/*",
'Content-Length': imageUrlPath!.length,
'Connection': 'keep-alive',
'User-Agent': 'ClinicPlush'
});
await Dio().put(imageUrlPath!,
data: Stream.fromIterable(profileImage.map((e) => [e])),
options: options);
}
I have tried in this way where profileImage is Uint8List image format

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]

Can't get auth token stored in flutter secure storage to headers

I am making flutter app using API and I have a problem. When I want to get auth token to make request, flutter says that "Expected a value of type 'String', but got one of type '_Future'". How can I make a request with auth token without that error?
My login function, where I write the token:
loginUser() async {
final storage = new FlutterSecureStorage();
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/login");
await http
.post(uri,
headers: {"Content-Type": "application/json"},
body: jsonEncode({
"username": emailController.text,
"password": passwordController.text
}))
.then((response) async {
if (response.statusCode == 200) {
var data = json.decode(response.body);
await storage.write(key: "token", value: data["token"]);
print(data["token"]);
} else {
print(json.decode(response.body));
}
});
}
My getdata function, where i use the token:
getdata() async {
final storage = FlutterSecureStorage();
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/countries");
await http.get(uri, headers: {
"Content-Type": "application/json",
"Authorization": await storage.read(key: "token")
});
}
try this code
String token = await storage.read(key: 'token');
//make sure if there is no Bearer just token in that case just pass the token
var headers = {
'accept': 'application/json',
'Authorization': 'Bearer ${token}',
};
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/countries");
Response response = await http.get(
uri,
headers: headers
);
print (response);

how post api with authentication identifier and secret in flutter

i want fetch data by post method with identifier and secret in flutter
where should i add "identifier" and "secret" in post method?
in postman they added to body and that works but i couldnt add these to flutter code:
Future post(String url, var data) async {
String url = 'https://member.example.com/includes/api.php';
var data = {
'identifier': 'identifier code otm7LE8OzlBmprXn',
'secret': 'secret code SXZgmDpX8miT31PSRQ',
'action': 'GetInvoices',
'userid': 6414,
'orderby': 'date',
'responstype': 'json',
};
try {
final response = await http.post(
Uri.parse(url),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
},
body: jsonEncode(data),
);
} catch (e) {
print(e);
}
}
E/flutter ( 6118): result=error;message=Authentication Failed

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?

I would like to upload a image and profile data in Multipart/Formdata format in flutter when hit a api i got response failed

Here is my post api code i try to upload file (image from image picker)and profilePojo(data like username ,fname, lastname etc.) when i run code i got result failed .
'''
void addData(final profilePojo) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
String token = preferences.getString('token');
FormData formData = FormData.fromMap({
"file": await MultipartFile.fromFile("./text.txt",filename: "upload.txt"),
"profilePojo":profilePojo,//profilePojo means i pass heaar string of data on button click
});
String url =pass here url
http
.post(
url,
headers: {
HttpHeaders.authorizationHeader: 'Bearer $token',
// "Content-Type":"multipart/form-data",
"accept": "application/json",
},
body: formData.toString()
)
.then((response) {
if (response.statusCode == 200) {
var myData = json.decode(response.body);
if(myData['result']=="success"){
setState(() {
print(myData);//print response success
_showDialog();
getData();
});}
else{
print(response.statusCode);
print(myData);
}
} else {
print(response.statusCode);
print("object");
}
});
}
'''
I'm currently using dio for this kind of requests, here is my example:
final futureUploadList = imageList.map((img) async {
print(img.path);
return MultipartFile.fromFile(img.path);
});
final uploadList = await Future.wait(futureUploadList);
FormData data = FormData.fromMap({
"images": uploadList
});
dio.post('/images',
data: data, options: Options(headers: {'Authorization': 'Bearer abcd'}));