Skip to content

Commit

Permalink
feat: 이미지 업로드 코드 service
Browse files Browse the repository at this point in the history
  • Loading branch information
HI-JIN2 committed Dec 18, 2024
1 parent 9c9b1b9 commit bb77843
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 77 deletions.
82 changes: 54 additions & 28 deletions lib/data/service/s3_service.dart
Original file line number Diff line number Diff line change
@@ -1,53 +1,79 @@
import 'dart:developer';
import 'dart:io';

import 'package:cogo/constants/apis.dart';
import 'package:cogo/data/di/api_client.dart';
import 'package:cogo/data/dto/response/base_response.dart';
import 'package:cogo/data/dto/response/image_save_response.dart';
import 'package:cogo/data/repository/local/secure_storage_repository.dart';
import 'package:dio/dio.dart';
import 'package:flutter_config/flutter_config.dart';

import '../../../constants/apis.dart';

class S3Service {
final ApiClient _apiClient = ApiClient();
static const apiVersion = "api/v2/";
final Dio _dio = Dio();
final SecureStorageRepository _secureStorage = SecureStorageRepository();

S3Service();

// s3 이미지 저장
Future<ImageSaveResponse> saveImage(File selectedImage) async {
Future<String?> uploadImage(String imagePath) async {
try {
String fileName = selectedImage.path.split('/').last;
log("fileName: $fileName");

FormData formData = FormData.fromMap({
"file": await MultipartFile.fromFile(
selectedImage.path,
filename: fileName,
),
// API 엔드포인트 URL
const apiVersion = "api/v2/";
final url = '${FlutterConfig.get("base_url")}$apiVersion${Apis.s3}/v2';

// 토큰 가져오기
var token = await _secureStorage.readAccessToken();

// FormData 생성
final formData = FormData.fromMap({
'image': await MultipartFile.fromFile(imagePath,
filename: imagePath.split('/').last)
});

log("formData: ${formData.files.length}");
// Dio 요청 옵션 설정
final options = Options(
headers: {
'accept': '*/*',
'Authorization': 'Bearer $token',
'Content-Type': 'multipart/form-data',
},
);

// 요청 전송
final response = await _dio.post(
url,
data: formData,
options: options,
);

final response = await _apiClient.dio.post(
options: Options(
extra: {'skipAuthToken': false, 'multipart': true}, //토큰 해제하지 않음
),
'${Apis.s3}/v2',
data: {'image': formData.files});
// Log Interceptor 추가
_dio.interceptors.add(LogInterceptor(
request: true,
requestHeader: true,
requestBody: true,
responseHeader: true,
responseBody: true,
error: true,
logPrint: (obj) {
log("서버통신 $obj");
},
));

if (response.statusCode == 201) {
//base response로 받는건 여기서 뿐임.
final baseResponse = BaseResponse<ImageSaveResponse>.fromJson(
response.data,
(contentJson) => ImageSaveResponse.fromJson(contentJson),
);
return baseResponse.content;
return baseResponse.content.savedUrl;
} else {
throw Exception('Failed to send verification code');
throw Exception('서버 통신 실패 ${response.statusCode}');
}
} on DioException catch (e) {
throw Exception('Error: ${e.response?.data ?? e.message}');
// Dio 특화된 에러 처리
throw Exception('업로드 중 오류 발생: ${e.response?.data ?? e.message}');
} catch (e) {
// 기타 모든 예외 처리
throw Exception('An unexpected error occurred: $e');
// 기타 예외 처리
throw Exception('업로드 중 오류 발생: ${e.toString()}');
}
}
}
}
60 changes: 11 additions & 49 deletions lib/features/mypage/image_upload_view_model.dart
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
import 'dart:developer';
import 'dart:io';

import 'package:cogo/constants/apis.dart';
import 'package:cogo/data/repository/local/secure_storage_repository.dart';
import 'package:dio/dio.dart';
import 'package:cogo/data/service/s3_service.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_config/flutter_config.dart';
import 'package:get_it/get_it.dart';
import 'package:image_picker/image_picker.dart';

class ImageUploadViewModel extends ChangeNotifier {
final SecureStorageRepository _secureStorage = SecureStorageRepository();
final Dio _dio = Dio();
final S3Service s3service = GetIt.instance<S3Service>();

File? _selectedImage;
bool _isUploading = false;
String? _uploadResult;
String? _errorMessage;

// 생성자
ImageUploadViewModel();

// Getters
File? get selectedImage => _selectedImage;
bool get isUploading => _isUploading;
Expand Down Expand Up @@ -72,53 +71,16 @@ class ImageUploadViewModel extends ChangeNotifier {
_errorMessage = null;
notifyListeners();

// API 엔드포인트 URL
const apiVersion = "api/v2/";
final url = '${FlutterConfig.get("base_url")}$apiVersion${Apis.s3}/v2';

// 토큰 가져오기
var token = await _secureStorage.readAccessToken();

// FormData 생성
final formData = FormData.fromMap({
'image': await MultipartFile.fromFile(_selectedImage!.path,
filename: _selectedImage!.path.split('/').last)
});

// Dio 요청 옵션 설정
final options = Options(
headers: {
'accept': '*/*',
'Authorization': 'Bearer $token',
'Content-Type': 'multipart/form-data',
},
);

// 요청 전송
final response = await _dio.post(
url,
data: formData,
options: options,
);

// 상태 코드 확인
if (response.statusCode != 201) {
throw Exception('업로드 실패: 상태 코드 = ${response.statusCode}');
}
// 서비스를 통해 이미지 업로드
_uploadResult = await s3service.uploadImage(_selectedImage!.path);

//todo 이미지 업로드 api
// 업로드 성공
_uploadResult = response.data.toString();
log(_uploadResult.toString());
_isUploading = false;
notifyListeners();
} on DioException catch (e) {
// Dio 특화된 에러 처리
_errorMessage = '업로드 중 오류 발생: ${e.response?.data ?? e.message}';
_isUploading = false;
notifyListeners();
} catch (e) {
// 기타 예외 처리
_errorMessage = '업로드 중 오류 발생: ${e.toString()}';
// 에러 처리
_errorMessage = e.toString();
_isUploading = false;
notifyListeners();
}
Expand Down

0 comments on commit bb77843

Please sign in to comment.