개발하슈
[android] retrofit2 file upload 이미지 업로드 본문
[참고자료]
https://velog.io/@dev_thk28/Android-Retrofit2-Multipart%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0-Java
https://machine-woong.tistory.com/171
https://philip1994.tistory.com/15
https://blog.naver.com/power95031/222139388370
https://jaejong.tistory.com/38
https://link2me.tistory.com/1806
php코드
header("Content-Type:text/html;charset=utf-8");
$data=$_POST["uploaded_file"];
$uploads_dir="./newImage";
$file_path = "./";
$basename = basename( $_FILES['uploaded_file']['name']);
$file_path = $file_path . $basename;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],"../$uploads_dir/$file_path")) {
$result =array("result" => "success");
echo "success";
} else{
$result = array("result" => "error");
echo "error";
android 코드
안드로이드 코드는 retrofit부분만 업로드함
public class ApiClient {
private static final String BASE_URL = "서버주소";
private static Retrofit retrofit;
public static Retrofit getApiClient()
{
Gson gson = new GsonBuilder()
.setLenient()
.create();
if (retrofit == null)
{
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
public interface RetrofitInterface {
//api를 관리해주는 인터페이스
@Multipart
@POST("upload_chat.php")
Call<String> request(@Part MultipartBody.Part file);
}
private void uploadChat(){
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", imageFileName, requestFile);
RetrofitInterface retrofitInterface=ApiClient.getApiClient().create(RetrofitInterface.class);
Call<String> call=retrofitInterface.request(body);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.e("uploadChat()", "성공 : ");
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("uploadChat()", "에러 : " + t.getMessage());
}
});
}
'android' 카테고리의 다른 글
[android] fragment 생명주기 (0) | 2021.12.10 |
---|---|
[android] Retrofit2 post 예제 (0) | 2021.05.28 |