gpt4 book ai didi

php - 同时创建文件夹和上传文件

转载 作者:行者123 更新时间:2023-12-01 05:25:28 25 4
gpt4 key购买 nike

我的代码遇到了问题。我知道我做错了什么,但我不知道是什么。我有一个照片上传表单,如果它不存在,它必须创建一个文件夹,并将图片上传到该文件夹​​。

所以我的问题是我不能同时做这两件事e。如果该文件夹已经存在,则上传图像,但如果该文件夹不存在,它只会创建该文件夹,我必须再次上传该图片才能进入该文件夹。

这是我的代码。

INDEX.HTML

<form action="" method="post" enctype="multipart/form-data">
<input id="input-image-3" class="file-loading" type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
</form>

<script>
$("#input-image-3").fileinput({
uploadUrl: "upload.php",
allowedFileExtensions: ["jpg","jpeg", "png", "gif"],
maxImageWidth: 100,
maxImageHeight: 100,
resizePreference: 'height',
maxFileCount: 10,
resizeImage: true,


}).on('filepreupload', function() {
$('#kv-success-box').html('');
}).on('fileuploaded', function(event, data) {
$('#kv-success-box').append(data.response.link);
$('#kv-success-modal').modal('show');
});

</script>

上传.PHP

<?php
$valid_formats = array("jpg", "png");
$max_file_size = 1024*100; //100 kb
$path = "up/test/"; // Upload directory, later i'll get the name of user
$filename=$file['filename'];
$extension = '.jpg';
$i=1;
while(file_exists($path.$filename.$extension)){
$filename=$file['filename']."teste_($i)";
$i++;}

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files

if(!is_dir($path)){mkdir($path, 0755);} // If dont exist, create folder

move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$filename.$extension);
}
}
}
}
echo json_encode (json_decode ("{}"));
?>

提前谢谢你,

最佳答案

尝试使用以下代码在新创建的目录中上传文件。

<?php
define("SITE_NAME","project_name/"); //constant for project name
define("SITE_PATH",$_SERVER['DOCUMENT_ROOT']."/".SITE_NAME); //constant for project base directory
define("IMAGES_URL",SITE_URL."images/"); //constant for image directory


$upload_base_dir=IMAGES_URL;
$upload_time_dir=date('Y')."/".date('m')."/".date('d')."/"; // setup directory name
$upload_dir = $upload_base_dir.$upload_time_dir;

if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true); //create directory if not exist
}

$image_name=basename($_FILES['image']['name']);
$image=time().'_'.$image_name;
move_uploaded_file($_FILES['image']['tmp_name'],$upload_dir.$image); // upload file
?>

关于php - 同时创建文件夹和上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36497463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com