is there any mistake while sending the data?
Image path is received correctly however the image is mandatory and not uploading
import 'dart:developer';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:real_estate_app/domain/core/api_end_points.dart';
class APIAddService {
static final Dio _dio = Dio();
static Future<void> addProperty({
required String accessToken,
required String propName,
required String propPrice,
required String propAge,
required int propStatus,
required int propType,
required String location,
required int availabilityStatus,
required List<String> spec,
required List<String> size,
required List<File> image,
}) async {
try {
String apiUrl = ApiEndPoints.addproperty;
List<MultipartFile> imageFiles = [];
for (File img in image) {
imageFiles.add(await MultipartFile.fromFile(
img.path,
filename: img.path.split('/').last,
));
}
FormData formData = FormData.fromMap({
"prop_name": propName,
"prop_price": propPrice,
"prop_status": propStatus,
"prop_type": propType,
"prop_age": propAge,
"location": location,
"availability_status": availabilityStatus,
"spec": spec,
"size": size,
"image": imageFiles,
});
log('imageFiles:$imageFiles');
log('images: ${image.map((file) => file.path).toList()}');
log('FormData: $formData');
log('formfields:${formData.fields}');
Options options = Options(headers: {
"access-token": accessToken,
});
Response response = await _dio.post(
apiUrl,
data: formData,
options: options,
);
print("Response status code: ${response.statusCode}");
print("Response data: ${response.data}");
if (response.statusCode == 200 && response.data['responseCode'] == 200) {
print("Property added successfully!");
} else {
print("Failed to add property. Response data: ${response.data}");
}
} catch (e) {
if (e is DioException) {
print("Dio Error: ${e.message}");
print("Dio Error Response: ${e.response?.data}");
} else {
print("Error: $e");
}
}
}
}
what is the right way to do it? I used the image_picker package to select multiple images, and then utilized Dio for sending server requests to upload them.
you missed to specify the content type ,use below snippet instead
List<MultipartFile> imageFiles = [];
for (File img in image) {
String fileName = basename(img.path);
String fileExtension = extension(fileName).substring(1);
imageFiles.add(await MultipartFile.fromFile(
img.path,
contentType: MediaType('image', fileExtension),
filename: fileName,
));
}