【问题标题】:uploading files in single page applications在单页应用程序中上传文件
【发布时间】:2018-04-06 12:38:21
【问题描述】:

目前我正在用 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();
}

【问题讨论】:

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


    【解决方案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')
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      相关资源
      最近更新 更多