본문 바로가기
PHP

[PHP] Retrofit 라이브러리를 사용해서 서버에 파일 업로드하기(서버)

by teamnova 2023. 10. 20.

https://stickode.tistory.com/962

 

이전 예제인 클라이언트편에 이어서 서버편의 예제를 작성해보도록 하겠습니다.

 

서버에서는 클라이언트에서 전송한 파일을 확인하고 특정 경로에 파일을 저장해줘야 합니다.

 

코드 동작 순서입니다.

1. 전송된 파일 확인

2. 확장자 확인 및 파일 저장 경로 설정

3. 설정한 경로에 파일 저장

 

 

send_img_test.php (클라이언트에서 요청한 내용을 수행하는 서버 PHP 파일)

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
try{

    include("retrofit_config.php");

    if ($_SERVER['REQUEST_METHOD'] == 'POST'){

        // .을 기준으로 파일 확장자 추출 (클라이언트에서 업로드할 때 사용한 파일 키를 사용해 업로드된 파일을 특정하고 파일 이름을 가져옴)
        $nameArr = explode(".",  $_FILES["file_key"]["name"]);
        $extension = $nameArr[sizeof($nameArr) - 1];

        // 파일 이름으로 사용할 현재시간 가져오기
        $microtime = DateTime::createFromFormat('U.u', microtime(true));
        $now = (int)subStr($microtime->format("ymdhisu"), 0, 16);

        // 파일 이름
        $file_name = $now.".".$extension;

        $target_dir = "img_tmp/"; // 파일을 저장할 위치
        $target_file_address = $target_dir.$file_name; // 파일 저장 최종 경로

        // 파일 업로드 (파일키와 서버의 임시 저장소에 저장된 파일이름을 사용해 파일 저장 최종 경로에 파일 저장)
        if(move_uploaded_file($_FILES["file_key"]["tmp_name"], $target_file_address)){
            // 파일 업로드 성공 시 결과값 success 반환
            echo json_encode(array(
                "status" => "success",
                "message" => "upload success"),
                JSON_UNESCAPED_UNICODE
            );
        }else{ // 업로드 중 에러 발생 시 결과값 fail 반환
            echo json_encode(array(
                "status" => "fail",
                "message" => "uploading file error"),
                JSON_UNESCAPED_UNICODE
            );
        }

    }else{ // POST method를 사용하지 않았을 경우 결과값 fail 반환
        echo json_encode(array(
            "status" => "fail",
            "message" => "wrong method"),
            JSON_UNESCAPED_UNICODE
        ); 
    }

}catch(Exception $e){ // 프로그램 실행 중 발생하는 비정상적인 상황을 잡아서 알려줌
    echo json_encode(array(
        "status" => "fail",
        "message" => "".($e->getMessage()))
    );
}catch(Error $e){ // 문법 오류, 미정의된 함수 호출, 변수 오류 등을 잡아서 알려줌
    echo json_encode(array(
        "status" => "fail",
        "message" => "".($e->getMessage()))
    );
}finally{ // db 연결 참조해제
    $connect = null;
}

?>

 

이렇게 클라이언트단의 코드와 서버단의 코드를 작성 완료했다면 프로그램을 실행했을 때 클라이언트에서 촬영한 사진을 서버에 저장할 수 있게 됩니다!!!