我的需求如下:当用户上传文件时,我应该检查"文件已经存在",如果文件存在,我必须显示确认框,如果"确定",我必须替换,如果取消,则相反。这是我的以下代码
if (file_exists($path . $documentName)) {
$msg = $documentName . " already exists. ";
?>
<script type="text/javascript">
var res = confirm('File already exists Do you want to replace?');
if (res == false) {
<?php
$msg = 'File Upload cancelled';
?>
} else {
<?php
if (move_uploaded_file($_FILES["document"]["tmp_name"], $path . $documentName)) {
$msg = $documentName . " File Replaced Successfully";
$successURL = $document_path . $documentName;
}
else
$msg = $documentName . "Upload Failed";
?>
}
</script>";
<?
}
我的问题是,即使我取消文件也会被替换。只要告诉我哪里错了,或者有其他方法吗?请帮我解决这个问题注意:不允许使用jquery。
您的问题是混合了javascript和PHP。PHP代码将在服务器上运行,并生成HTML文档。此时,文件已被替换。
然后,这个文档(里面有javascript代码)将被发送给用户,并在那里运行javascript代码。在那一刻,用户可以看到确认对话框,即使文件已经被替换!
看看php代码正在生成的源代码,你就会明白我的意思。
解决方案是添加一个复选框来确认覆盖文件。然后,在点击上传/提交按钮后,php脚本将检查是否选中了此框,并替换文件或不替换文件。
@Gogul,老实说,这不是正确的做法。最好使用AJAX请求来处理文件提交,AJAX请求会从您的服务器(成功上传或文件存在)收到响应,您可以适当地处理该响应。如果向用户提供替换文件的选项,请再次使用AJAX处理该操作。
您可以在原始JavaScript中执行AJAX请求(不需要jQuery)-请参阅此处:http://www.w3schools.com/ajax/ajax_xmlhttprequestrongend.asp
您正在混合服务器端代码和客户端javascript。如果你不想让用户重新部署文档,那么问题的解决就更复杂了:
- 将文件存储在随机文件名下的临时位置。向用户输出一个是/否表单,包括随机文件名和原始文件名
- 如果用户回答是,则从临时位置移动到$path,否则从临时位置删除文件
Guys我带来了以下解决方案上传
上传document.php
$documentName = preg_replace('/[^a-zA-Z0-9.]/s', '_', $_FILES["document"]["name"]);
if (file_exists($path . $documentName)) {
move_uploaded_file($_FILES["document"]["tmp_name"], "F:''Content''enews_files''temp''" . $documentName);
$msg = $documentName . " already exists. <a href='confirm.php?confirm=1&filename=" . $documentName . "&language=" . $lang . "'>Replace</a>||<a href='confirm.php?confirm=0&filename=" . $documentName . "'>Cancel</a>";
} else {
if (move_uploaded_file($_FILES["document"]["tmp_name"], $path . $documentName)) {
$msg = $documentName . " Upload Success";
$successURL = $document_path . $lang . '/' . $documentName;
}
else
$msg = $documentName . " Upload Failed";
}
confirm.php
include("config_enews.php");
$lang = $_GET['language'];
$path = "F:''Content''enews_files''" . $lang . "''";
//$path = "D:''test''test''" . $lang . "''";
$documentName = preg_replace('/[^a-zA-Z0-9.]/s', '_', $_GET["filename"]);
if ($_GET['confirm'] == 1) {
//echo sys_get_temp_dir();die;
if (copy("F:''Content''enews_files''temp''" . $_GET["filename"], $path . $documentName)) {
unlink("F:''Content''enews_files''temp''" . $_GET["filename"]);
header("Location: uploaddocument.php?message=success&fname=$documentName&lang=$lang");
} else {
echo $res = move_uploaded_file($_GET["tempname"], $path . $documentName);
echo $msg = $documentName . " Upload Failed";
header("Location: uploaddocument.php?message=failed&fname=$documentName");
}
} else {
unlink("F:''Content''enews_files''temp''" . $_GET["filename"]);
header("Location: uploaddocument.php?message=cancelled&fname=$documentName");
}
我从@Marek那里得到了这个火花。如果有人有更好的解决方案,请提供。
对不起,我没有足够的声誉来投票给你。
非常感谢您的支持。