通过xmlhttprequest发送带有userid的字符串和文件

sending string with userid together with files through xmlhttprequest

本文关键字:字符串 文件 userid xmlhttprequest 通过      更新时间:2023-09-26

我使用以下代码在不刷新页面的情况下上传文件,但我需要将当前登录用户的userid与文件一起发送,该文件存储在$_SESSION['userid']中。

var fileSelect = document.getElementById('file');
var files = fileSelect.files;
var formData = new FormData();
var div = document.getElementById('UploadInfo');
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
    var file = files[i];
    // Check the file type.
    if (!file.type.match('image.*')) {
        alert("File: " + file.name + " is not an image and will not be uploaded.");
        continue;
    }
    // Add the file to the request.
    formData.append('images[]', file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'Php/upload_file.php', true);
xhr.send(formData);

我尝试过使用以下行,但没有成功,这意味着我在phpscript中没有收到userid值,$_POST为空,$_FILES只包含fileinfo。

formData.append('UserID', '<%=$_SESSION["UserID"] %>');

我还有其他方法可以做到这一点吗?

我的PHP代码:

if(isset($_FILES)) {
$numberOfFiles = count($_FILES['images']['name']);
for($id = 0; $id < $numberOfFiles; $id++)
{
    if (file_exists($_FILES["images"]["tmp_name"][$id])) {
        $destination = "../UploadedImages/" . $_FILES['UserID'] . $_FILES["images"]["name"][$id];
        move_uploaded_file($_FILES["images"]["tmp_name"][$id], $destination);
    }
}

}

exit();

看起来你需要在php脚本中使用$_POST,你有$_FILES['UserID']而不是$_POST['UserID']。我还添加了一个检查UserID是否已传递,并添加了变量$UserID,如果$_POSD['UserID']没有传递到php脚本,我会使用die并发回一个错误。

注意:您应该检查$_POST['UserID'],以确保它不包含SQL注入脚本或可能导致问题的有害代码。

if(isset($_FILES) || isset($_POST)) {
    $numberOfFiles = count($_FILES['images']['name']);
    $userId = ''; //Create userId variable
    //Check if the UserID exists in the autoglobal $_POST
    if(array_key_exists('UserID', $_POST) === true) { 
        //Now we can add UserId to our variable
        $userId = $_POST['UserID']; 
    } else { 
        die('UserID was not passed');
    }
    for($id = 0; $id < $numberOfFiles; $id++)
    {
        if (file_exists($_FILES["images"]["tmp_name"][$id])) {
            $destination = $userId . $_FILES["images"]["name"][$id];
            move_uploaded_file($_FILES["images"]["tmp_name"][$id], $destination);
        }
    }

} else {
   echo "$_POST and $_FILES dont exist";
}

编辑:修复了一些语法错误,请重新查看代码并确保您有最新版本。