Skip to content

Commit

Permalink
feat: imageUrl을 이용해서 서버에 저장
Browse files Browse the repository at this point in the history
  • Loading branch information
HI-JIN2 committed Dec 18, 2024
1 parent bb77843 commit 4f18f33
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 55 deletions.
4 changes: 0 additions & 4 deletions lib/data/di/api_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,6 @@ class ApiClient {
options.headers['Authorization'] = 'Bearer $token';
}
}
// if (options.extra['multipart']==true){
// options.headers.remove('Content-Type');
// options.headers['Content-Type'] = ' multipart/form-data';
// }
log('요청 보내는 중: ${options.method} ${options.path}');
return handler.next(options);
},
Expand Down
70 changes: 19 additions & 51 deletions lib/data/service/s3_service.dart
Original file line number Diff line number Diff line change
@@ -1,73 +1,41 @@
import 'dart:developer';

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:cogo/constants/apis.dart';
import 'package:cogo/data/di/api_client.dart';
import 'package:dio/dio.dart';
import 'package:flutter_config/flutter_config.dart';

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

class S3Service {
final Dio _dio = Dio();
final SecureStorageRepository _secureStorage = SecureStorageRepository();

S3Service();
final ApiClient _apiClient = ApiClient();
static const apiVersion = "api/v2/";

Future<String?> uploadImage(String imagePath) async {
try {
// API 엔드포인트 URL
const apiVersion = "api/v2/";
final url = '${FlutterConfig.get("base_url")}$apiVersion${Apis.s3}/v2';

// 토큰 가져오기
var token = await _secureStorage.readAccessToken();
const url = '$apiVersion${Apis.s3}/v2';

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

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

// 요청 전송
final response = await _dio.post(
final response = await _apiClient.dio.post(
url,
data: formData,
options: options,
options: Options(
headers: {
'accept': '*/*',
'Content-Type': 'multipart/form-data',
},
),
);

// 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.savedUrl;
} else {
throw Exception('서버 통신 실패 ${response.statusCode}');
// 상태 코드 확인
if (response.statusCode != 201) {
throw Exception('업로드 실패: 상태 코드 = ${response.statusCode}');
}

// 업로드 성공
return response.data.toString();
} on DioException catch (e) {
// Dio 특화된 에러 처리
throw Exception('업로드 중 오류 발생: ${e.response?.data ?? e.message}');
Expand All @@ -76,4 +44,4 @@ class S3Service {
throw Exception('업로드 중 오류 발생: ${e.toString()}');
}
}
}
}
30 changes: 30 additions & 0 deletions lib/data/service/user_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,34 @@ class UserService {
throw Exception('An unexpected error occurred: $e');
}
}

///PUT /api/v2/users/picture 이미지 저장하기
Future<bool> saveImage(String imageUrl) async {
try {
final response =
await _apiClient.dio.put(apiVersion + Apis.saveImage, data: imageUrl);

//todo 여기 response가 존재하나 필요가 없어서 안받음
// {
// "statusCode": "201",
// "message": "CREATED",
// "content": {
// "username": "113343694546635833713",
// "name": "222",
// "email": "objet917@gmail.com",
// "role": "ROLE_MENTOR",
// "phoneNum": "123-1231-2312",
// "picture": "\"https://cogo-bucket.s3.ap-northeast-2.amazonaws.com/v2/113343694546635833713\""
// }
// }
if (response.statusCode != 201) {
throw Exception('Failed to send verification code ${response.data}');
}
return true;
} on DioException catch (e) {
throw Exception('Error: ${e.response?.data ?? e.message}');
} catch (e) {
throw Exception('An unexpected error occurred: $e');
}
}
}
7 changes: 7 additions & 0 deletions lib/features/mypage/image_upload_view_model.dart
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import 'dart:io';

import 'package:cogo/data/service/s3_service.dart';
import 'package:cogo/data/service/user_service.dart';
import 'package:flutter/foundation.dart';
import 'package:get_it/get_it.dart';
import 'package:image_picker/image_picker.dart';

class ImageUploadViewModel extends ChangeNotifier {
final S3Service s3service = GetIt.instance<S3Service>();
final UserService userService = GetIt.instance<UserService>();

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

Expand All @@ -19,6 +22,8 @@ class ImageUploadViewModel extends ChangeNotifier {
// Getters
File? get selectedImage => _selectedImage;
bool get isUploading => _isUploading;

bool get isUpload => _isUpload;
String? get uploadResult => _uploadResult;
String? get errorMessage => _errorMessage;

Expand Down Expand Up @@ -75,7 +80,9 @@ class ImageUploadViewModel extends ChangeNotifier {
_uploadResult = await s3service.uploadImage(_selectedImage!.path);

//todo 이미지 업로드 api

// 업로드 성공
_isUpload = await userService.saveImage(_uploadResult!);
_isUploading = false;
notifyListeners();
} catch (e) {
Expand Down

0 comments on commit 4f18f33

Please sign in to comment.