在单页面应用程序中上传文件

时间:2017-10-25 12:12:40

标签: javascript php ajax ecmascript-6 fetch-api

目前我正在使用ES6 + PHP构建单页面应用程序,并且在ajax调用方面存在一些问题。我找不到任何通过fetch API上传文件的例子,老实说,我不知道ajax调用应该是这样的,因为如何在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 个答案:

答案 0 :(得分:1)

您可以稍微简化一下FETCH语句。 fetch的一个好处是它会尝试为你应用正确的内容类型。因为你也试图上传文件,你需要将_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
});

甚至更好地使用async / await

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')
}