54 lines
1.7 KiB
Dart
54 lines
1.7 KiB
Dart
import 'package:dartz/dartz.dart';
|
|
import 'package:dio/dio.dart';
|
|
import 'package:enaklo_pos/core/constants/variables.dart';
|
|
import 'package:enaklo_pos/core/network/dio_client.dart';
|
|
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
|
import 'package:enaklo_pos/data/models/response/file_response_model.dart';
|
|
|
|
class FileRemoteDataSource {
|
|
final Dio dio = DioClient.instance;
|
|
|
|
Future<Either<String, FileResponseModel>> uploadFile({
|
|
required String filePath,
|
|
required String fileType,
|
|
required String description,
|
|
}) async {
|
|
final url = '${Variables.baseUrl}/api/v1/files/upload';
|
|
|
|
try {
|
|
final authData = await AuthLocalDataSource().getAuthData();
|
|
|
|
// Membuat FormData
|
|
final formData = FormData.fromMap({
|
|
'file': await MultipartFile.fromFile(filePath,
|
|
filename: filePath.split('/').last),
|
|
'file_type': fileType,
|
|
'description': description,
|
|
});
|
|
|
|
final response = await dio.post(
|
|
url,
|
|
data: formData,
|
|
options: Options(
|
|
headers: {
|
|
'Authorization': 'Bearer ${authData.token}',
|
|
'Accept': 'application/json',
|
|
// Content-Type otomatis diatur oleh Dio untuk FormData
|
|
},
|
|
),
|
|
);
|
|
|
|
if (response.statusCode == 201 || response.statusCode == 200) {
|
|
// Misal response.data['url'] adalah URL file yang diupload
|
|
return Right(FileResponseModel.fromJson(response.data));
|
|
} else {
|
|
return Left('Upload gagal: ${response.statusMessage}');
|
|
}
|
|
} on DioException catch (e) {
|
|
return Left(e.response?.data['message'] ?? 'Upload gagal');
|
|
} catch (e) {
|
|
return Left('Unexpected error: $e');
|
|
}
|
|
}
|
|
}
|