2017-10-25 1 views
1

현재 저는 ES6 + PHP에서 단일 페이지 응용 프로그램을 작성 중이며 ajax 호출에 몇 가지 문제가 있습니다. 가져 오기 API를 통해 파일 업로드 예제를 찾을 수 없으며 솔직히 아약스 호출이 PHP에서 데이터를 읽는 방법 때문에 이런 식으로 표시되어야한다는 단서가 없습니다.단일 페이지 응용 프로그램에서 파일 업로드

이와 비슷한 형식은 백엔드에 양식을 보내야합니다. 이것은 내가 지금까지 무엇을 가지고,하지만 작동하지 않습니다 깨끗한 솔루션 :(

JS 생각할 수 없다 :

const headers = new Headers({ 
    'Accept':'application/json', 
    'Content-Type':'application/json' 
}); 

class User{ 
    constructor(){ 
     this._ajaxData = {}; 
    } 

    /** 
    * @param {object} curObj 
    * @param {int} curObj.ID 
    * @param {HTMLElement} curObj.InputDate 
    * @param {HTMLElement} curObj.Username 
    * @param {HTMLElement} curObj.UploadFile = <input type='file'> 
    */ 
    collectInputData(curObj){ 
     this._ajaxData = { 
      UserID: curObj.ID, 
      ChangeDate: curObj.InputDate.value, 
      Username: curObj.Username.value, 
      SomeFile: curObj.UploadFile 
     }; 
    } 

    doAjax(){ 
     let _ajaxData = this._ajaxData; 
     let request = new Request("ajax/saveUser.php", { 
      method : "POST", 
      headers: headers, 
      body : JSON.stringify(_ajaxData) 
     }); 

     fetch(request).then(function (res) { 
      return res.json(); 
     }).then(function (data) { 
      console.log(data); 
     }); 
    } 
} 

PHP :

require_once __DIR__.'/../vendor/autoload.php'; 
$PDO = \DBCon::getInstance(); 

$data = json_decode(file_get_contents('php://input')); 

$PDO->beginTransaction(); 

$_FILES["fileToUpload"]["name"] 

$User = new \User(); 
$User->setUserID($data->UserID); 
$User->setChangeDate($data->ChangeDate); 
$User->setUsername($data->Username); 
/** 
* to use like with $_FILES["fileToUpload"] 
* 
* @param array $data->SomeFile 
*/ 
$User->setUploadFiles($data->SomeFile); 


$User->save(); 
try{ 
    $PDO->commit(); 
    echo true; 
}catch(PDOException $e){ 
    echo $e->getMessage(); 
} 

답변

1

을 잘 가져 오기에 대한 좋은 점 중 하나는 올 Y 른 내용 유형을 적용하려고 시도한다는 것입니다. 파일을 올리려고하기 때.에 _ajaxData을 FormData로 전달해야합니다() 객체를 사용할 수 있습니다. 일부 사용자 정의 헤더를 전달하거나 컨텐츠 유형을 직접 정의하려고합니다. 다음은 일부 데이터를 업로드하는 fetch 문 예입니다.

let _ajaxData = new FormData(); 
_ajaxData.append("UserID", curObj.ID); 
_ajaxData.append("ChangeDate", curObj.InputDate.value); 
_ajaxData.append("Username", curObj.Username.value); 
_ajaxData.append("SomeFile", document.getElementById("fileInputId").files[0]) 

let saveUser = fetch("ajax/saveUser.php", { 
    method: "POST", 
    body: _ajaxData 
}); 

saveUser.then(result => { 
    //do something with the result 
}).catch(err => { 
    //Handle error 
}); 

또는 더 나은 사용 비동기

은/기다리고

const saveUser = async (_ajaxData) => { 
    let results = await fetch("ajax/saveUser.php", { 
     method: "POST", 
     body: _ajaxData 
    }); 
    if(results.ok){ 
     let json = await results.json(); 
     return json; 
    } 
    throw new Error('There was an error saving the user') 
} 
관련 문제