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]
Related
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
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
Postman form-data request
Request body containing
Expected Response body
Dio Flutter code
import 'package:dio/dio.dart';
import 'package:flutter_project/config/config.dart';
import '../model/postImage.dart';
import 'dart:io';
Future<PostImage> postImage(File image) async{
String fileName = image.path.split('/').last;
print(fileName);
try{
Dio dio = new Dio();
FormData formData = FormData.fromMap({
"file": await MultipartFile.fromFile(image.path,filename: fileName)
});
Map<String, String> headers= <String,String>{
'Content-Type':'multipart/form-data'
};
print("${baseURL}files/upload");
Response response = await dio.post("${baseURL}files/upload",data: formData);
if(response.statusCode == 200){
print("Uploaded");
}
else{
print(response.data);
}
}
catch(e){
print(e);
}
}
Expection that I am getting : DioError [DioErrorType.RESPONSE]: Http status error [404]
I added contentType: new MediaType("image", "jpeg")//in the formData. It works now.
Full Code :
import 'package:dio/dio.dart';
import 'package:flutter_project/config/config.dart';
import '../model/postImage.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
Future<PostImage> postImage(File image) async {
String fileName = image.path.split('/').last;
print(fileName);
try {
Dio dio = new Dio();
FormData formData = FormData.fromMap({
"file": await MultipartFile.fromFile(
image.path,
filename: fileName,
contentType: new MediaType("image", "jpeg"),
)
});
Map<String, String> headers = <String, String>{
'Content-Type': 'multipart/form-data'
};
print("${baseURL}files/upload");
Response response =
await dio.post("${baseURL}files/upload", data: formData);
if (response.statusCode == 200) {
print("Uploaded");
} else {
print(response.data);
}
print('Out');
} catch (e) {
print(e);
}
}
When I encountered an HTTP 4xx error while using Dio and I was sure I had my Authorization set, what I did to make it work is to set the Options() parameter explicitly. Precisely, I set the method type (for a get request) and authorisation token like this: Dio().get(url, options: Options(method: "GET", headers: { "Authorization": "Bearer ${LocalStorage().getString(Keys.token)}", })));.
You can also set content-type if need be. To make it easier, you can simply copy-paste into the headers: argument, some of the header values set in/by your postman when you make the same request using postman.
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 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');
});