我正在尝试检索上传文件的名称并将其附加到.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上?
下面是javascript函数,其中$ _SESSION变量在json代码中,通过将其附加到.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>
在单独的页面上,我有一个JSON,它检索$ _SESSION:
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;
}
答案 0 :(得分:3)
$_SESSION ['fileImage'][] = $_FILES ['fileImage']['name'];
代替$_SESSION ['fileImage']['name'] = $_FILES ['fileImage']['name'];