我在互联网上找到了一个如何使用ajax和php上传多个文件的解决方案。在ajax请求中,我传递的文件选择要上传的文件,但我需要再添加一个参数,但是当我这样做时,它无法正常工作。我不擅长PHP,我尝试在很多方面传递第二个参数但没有工作。如何传递第二个参数,以便一切都能正常工作?
HTML:
<form method="post" enctype="multipart/form-data">
Select files to upload:
<input name="file[]" type="file" multiple>
<input type="button" onclick="upload(this)" value="Upload"/>
</form>
的javascript:
function upload(element) {
var formData = new FormData($(element).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
success: function (callback) {
// some code
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
PHP
<?php
$mysqli = include 'connection.php';
$total = count($_FILES['file']['name']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
for ($i = 0; $i < $total; $i++) {
$name = $_FILES['file']['name'][$i];
$size = $_FILES['file']['size'][$i];
$location = 'uploads/';
$target_file = $location . basename($name);
if (isset($name)) {
if (empty($name)) {
echo 'Please choose a file' . "\n";
} else if (file_exists($target_file)) {
echo 'File already exists.' . "\n";
} else if ($size > 1000000) {
echo 'File is too large' . "\n";
} else {
$tmp_name = $_FILES['file']['tmp_name'][$i];
$statement = $mysqli->prepare("INSERT INTO files (name, subjectId) VALUES (?, ?)");
$str = '1'; // here I would like to set variable using $_POST
$statement->bind_param('ss', $name, $str);
if (move_uploaded_file($tmp_name, $location . $name)) {
if ($statement->execute()) {
echo 'File successfully uploaded :' . $location . $name . "\n";
} else {
echo 'Error while executing sql' . "\n";
}
} else {
echo 'Error while uploading file on server' . "\n";
}
}
}
}
}
所以我想要的是在javascript中添加第二个参数:
data: formData, mySecondParameter
然后在php中当我为sql绑定params时,我想输入我从javascript传递的变量:
$str = $_POST['contentOfMySecondParameter'];
答案 0 :(得分:4)
您可以使用FormData.append()
添加更多参数。
var formData = new FormData($(element).parents('form')[0]);
formData.append('mySecondParameter', contentOfMySecondParameter);
然后在PHP中使用$_POST['mySecondParameter']
来获取此参数。
答案 1 :(得分:0)
最简单的方法,添加
<input type='hidden' name='contentOfMySecondParameter' value='???' />
到HTML。您将在php中获得$_POST['contentOfMySecondParameter']
。
答案 2 :(得分:0)
只能在那里传递一个对象。如果你想要另一个变量,只需将它附加到formData,如下所示:
var formData = new FormData($(element).parents('form')[0]);
formData.append("mySecondParameter", mySecondParameter);
$.ajax({
...
data: formData,
...