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

uploading files in single page applications

目前我正在用 ES6 + PHP 构建一个单页应用程序并且在 ajax 调用方面遇到了一些问题。我找不到通过 fetch API 上传文件的任何示例,老实说,由于如何读取 PHP 中的数据,我不知道 ajax 调用是否应该看起来像这样.

类似这样的事情应该向后端发送一个表单。 这是我到目前为止得到的,但它不起作用,也想不出一个干净的解决方案:(

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();
}

好吧,您可以稍微简化 FETCH 语句。关于 fetch 的好处之一是它会尝试为 you.Since 应用正确的内容类型,您正在尝试上传文件,您还需要将 _ajaxData 作为 FormData() object。此外,您不需要 headers 除非您要传递一些自定义 headers 或想自己定义 content-type。下面是一个示例 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')
}