我正在尝试检索上传文件的名称并将其附加到 .list 中。问题是它从 $_SESSION 变量中检索的文件名始终是最后更新的文件,然后它不会改变。
例如,如果我在服务器中上传以下这些文件:
desert.jpg
tulips.jpg
lighthouse.jpg
desert_2.jpg
那么它应该从 $_SESSION 附加的文件名应该是:
desert.jpg
tulips.jpg
lighthouse.jpg
desert_2.jpg
但相反,它在屏幕上为从 $_SESSION 检索到的文件名附加了以下内容:
desert.jpg
desert.jpg
desert.jpg
desert.jpg
如何解决这个问题,以便在将文件上传到服务器时,将其文件名附加到 .list 上?
下面是 $_SESSION 变量在 json 代码中的 javascript 函数,它通过将文件名附加到 .list 上来在屏幕上显示文件名:
function stopImageUpload(success){
var imagename = <?php echo json_encode(isset($_SESSION ['fileImage']['name']) ? $_SESSION ['fileImage']['name'] : null); ?>;
if (success == 1){
$('.listImage').append(imagename + '<br/>');
}
else {
$('.listImage').append('No File');
}
return true;
}
下面是它上传文件的php代码:
<?php
session_start();
$result = 0;
$errors = array ();
$dirImage = "ImageFiles/";
$allowedTypes = array (
"image/jpeg",
"image/gif",
"image/pjpeg",
"image/jpg",
"image/png",
"image/tif"
);
if (isset ( $_FILES ['fileImage'] ) && $_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {
$fileName = $_FILES ['fileImage'] ['name'];
$fileSize = $_FILES ['fileImage'] ['size'];
$fileTemp = $_FILES ['fileImage'] ['tmp_name'];
$fileType = $_FILES ['fileImage'] ['type'];
$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExt = strtolower ( $fileExt );
if (empty ( $fileName ))
continue;
if (! in_array ( $fileType, $allowedTypes )) {
$errors [] = "File Type is not accepted";
}
if(!is_writable($dirImage ))
{
$errors [] = "File Destination not writeable";
}
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;
$filePrifix = basename ( $fileName, "." . $fileExt );
$i = 0;
while ( file_exists ( $fileDst ) ) {
$i ++;
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $filePrifix . "_" . $i . "." . $fileExt;
}
// Move the file
if (count ( $errors ) == 0) {
if (move_uploaded_file ( $fileTemp, $fileDst )) {
$result = 1;
}
}
}
$_SESSION ['fileImage'][] = $_FILES ['fileImage']['name'];
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result;?>);</script>
在单独的页面上,我有一个检索 $_SESSION 的 JSON:
function stopImageUpload(success){
var imagename = <?php echo json_encode(isset($_SESSION ['fileImage']) ? $_SESSION ['fileImage'] : null); ?>;
if (success == 1){
$('.listImage').append(imagename + '<br/>');
}
else {
$('.listImage').append('<br/>');
}
return true;
}