PHP에서 JSON으로 넘겨주기

PHP에서 JSON으로 넘겨주기

QA

PHP에서 JSON으로 넘겨주기

본문

받는 쪽의 자바스크립트


const genUploadedLabel =
    (editorElement: HTMLPreElement, responseText: string, vditor: IVditor) => {
        editorElement.focus();
        const response = JSON.parse(responseText);
 
        if (response.code === 1) {
            vditor.tip.show(response.msg);
        }
 
        if (response.data.errFiles) {
            response.data.errFiles.forEach((data: string) => {
                const lastIndex = data.lastIndexOf(".");
                const filename = vditor.options.upload.filename(data.substr(0, lastIndex)) + data.substr(lastIndex);
                const original = `[${filename}](${i18n[vditor.options.lang].uploading})`;
                setSelectionByInlineText(original, editorElement.childNodes);
                insertText(vditor, "", "", true);
            });
        }
 
        Object.keys(response.data.succMap).forEach((key) => {
            const path = response.data.succMap[key];
            const lastIndex = key.lastIndexOf(".");
            const filename = vditor.options.upload.filename(key.substr(0, lastIndex)) + key.substr(lastIndex);
            const original = `[${filename}](${i18n[vditor.options.lang].uploading})`;
            if (path.indexOf(".wav") === path.length - 4) {
                setSelectionByInlineText(original, editorElement.childNodes);
                insertText(vditor, `<audio controls="controls" src="${path}"></audio>\n`, "", true);
                return;
            }
            setSelectionByInlineText(original, editorElement.childNodes);
            insertText(vditor, `[${filename}](${path})`, "", true);
        });
    };

 

넘겨주는 PHP code https://sir.kr/g5_plugin/5218 의 일부


for ($i = 0; $i < count($_FILES["file"]["name"]); $i++) {
    $isUpload = is_uploaded_file($_FILES['file']['tmp_name'][$i]);
    // SUCCESSFUL
    if ($isUpload) {
        $ym = date('ym', G5_SERVER_TIME);
    
        // $data_dir =  '/editor/' . $ym;
        $data_dir = G5_DATA_PATH . '/editor/' . $ym;
        $data_url =  '/data/editor/' . $ym;
        // $data_url = G5_DATA_URL . '/editor/' . $ym;
    
        ($data_dir, G5_DIR_PERMISSION);
        @chmod($data_dir, G5_DIR_PERMISSION);
    
        $tmp_name = $_FILES['file']['tmp_name'][$i];
        $name = $_FILES['file']['name'][$i];
    
        $filename_ext = strtolower(array_pop(explode('.', $name)));
        $mime_result = ' ' . @mime_content_type($tmp_name) . @shell_exec('file -bi ' . $tmp_name);
    
        // thanks to @dewoweb 
        if (!preg_match("/(jpe?g|gif|bmp|png)$/i", $filename_ext)) {   // check file extension 
            // error
            @unlink($tmp_name);
            $errFiles[$i] = array('success' => false, 'error' => 100); // file type error 
        } else if (
            !stripos($mime_result, 'jpeg') &&                           // check file mime-type 
            !stripos($mime_result, 'jpg') &&
            !stripos($mime_result, 'gif') &&
            !stripos($mime_result, 'bmp') &&
            !stripos($mime_result, 'png')
        ) {
            @unlink($tmp_name);
            $errFiles[$i] = array('success' => false, 'error' => 101);
        } else if (!getimagesize($tmp_name)) {                              // check image resolution, if resolutions is null, return fail 
            @unlink($tmp_name);
            $errFiles[$i] = array('success' => false, 'error' => 102);
        } else {
    
            $file_name = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR'])) . '_' . get_microtime() . "." . $filename_ext;
            $save_dir = sprintf('%s/%s', $data_dir, $file_name);
            $save_url = sprintf('%s/%s', $data_url, $file_name);
    
            @move_uploaded_file($tmp_name, $save_dir);
    
            // $json[$i] = array( $name => $save_url);
            $data->$name = $save_url;
        }
    } else {
        $error = $_FILES['file']['error'][$i];
    
        // refer to error code : http://www.php.net/manual/en/features.file-upload.errors.php
        // example)  1 is error for upload_max_filesize 
        // echo json_encode(array('success'=> false, 'error' => $error));
        $errFiles[$i] = array('success' => false, 'error' => $error   );
    }
 }

는 어떻게 되어야 되나요?

 

대략 data는 넘겨서 동작되는 것을 확인 했는데,  에러가 났을 경우에 어떤식으로 변경해 주면 되는지요?

 

$test = array('succMap' => $data, 'errFiles' => []);

echo json_encode(array('code' => 1, 'msg' => "파일이 성공적으로 업로드되었습니다.", "data" => $test));

 

에러코드는 


switch(parseInt(obj.error)) {
    case 1: alert("업로드 용량 제한에 걸렸습니다."); break; 
    case 2: alert("MAX_FILE_SIZE 보다 큰 파일은 업로드할 수 없습니다."); break;
    case 3: alert("파일이 일부분만 전송되었습니다."); break;
    case 4: alert("파일이 전송되지 않았습니다."); break;
    case 6: alert("임시 폴더가 없습니다."); break;
    case 7: alert("파일 쓰기 실패"); break;
    case 8: alert("알수 없는 오류입니다."); break;
    case 100: alert("이미지 파일이 아닙니다.(jpeg, jpg, gif, bmp, png 만 올리실 수 있습니다.)"); break; 
    case 101: alert("이미지 파일이 아닙니다.(jpeg, jpg, gif, bmp, png 만 올리실 수 있습니다.)"); break; 
    case 102: alert("0 byte 파일은 업로드 할 수 없습니다."); break;
}

 

여기 참조

https://www.php.net/manual/en/features.file-upload.errors.php

 

포맷에 맞게 errFiles를 넘겨주면서 에러 메시지도 넣을수 있게 부탁드립니다. (PHP가 너무 어려운 1인)

 

 

 

 

이 질문에 댓글 쓰기 :

답변을 작성하시기 전에 로그인 해주세요.
전체 14,899
QA 내용 검색
filter #php ×

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT