通过xmlhttprequest发送带有userid的字符串和文件
sending string with userid together with files through xmlhttprequest
我使用以下代码在不刷新页面的情况下上传文件,但我需要将当前登录用户的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";
}
编辑:修复了一些语法错误,请重新查看代码并确保您有最新版本。
相关文章:
- 如何在JS文件中获取资源(.resx)字符串
- 使用JSON文件中的变量(字符串)填充文本区域
- 将HTML(支持文件)中的令牌(字符串、数字等)传递给LogiXML
- node.js将字符串转换为要上传到Web服务器的文件
- 将大数组(字符串和类型数组的混合物)存储到blob或文件中/从blob或文件检索大数组的最佳方式
- 从表单中动态生成一个字符串,传递给通过AJAX加载的PHP文件
- 将文件的内容读取为Javascript中的字符串
- 使用JavaScript将压缩文本文件加载到字符串中
- 使用gulp-angular gettext从JS文件中提取字符串不起作用
- 将字符串文件类型/权限转换为数字
- 我可以在两个javascript文件之间传递一个字符串吗?
- 为什么我在 webpack 中需要 html 文件时会得到一个位置字符串
- 如何将JS字符串解释为文件或在Bundlebars中使用字符串
- 为什么不是'当试图使用Ajax和外部PHP文件发布内容时,我的表单工作不正常,该文件接收两个字符串
- 解析CSV文件中的字符串
- 传递字符串的普通$.post()和传递文件的有什么区别
- 通过php文件替换多个字符串
- Eclipse Phonegap无法使用jquery.load函数加载外部字符串文件
- JS-html5文件阅读器API-获取二进制字符串文件并通过ajax发送
- 将字符串文件路径从子窗口传递到asp.net中的打开器:如何防止反斜杠被删除