【问题标题】:Create folder and upload file at the same time同时创建文件夹和上传文件
【发布时间】:2023-04-09 02:45:01
【问题描述】:

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

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

这是我的代码。

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>

UPLOAD.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 ("{}"));
?>

提前谢谢你,

【问题讨论】:

  • 试试 $oldumask = umask(0); mkdir($path, 0777,TRUE); umask($oldumask);我用这个技巧
  • 你好,@SameerJain。感谢您的帮助,我已尝试添加该代码,但不幸的是,这也不起作用。它一次只做一个动作。

标签: php file-upload image-uploading mkdir


【解决方案1】:

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

<?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
?>

【讨论】:

    【解决方案2】:

    if(!is_dir($path)){mkdir($path, 0755); 将其更改为 777 并检查是否有帮助 或者试试这个

    >     if(isset($_FILES["fileToUpload"]["name"]) && $_FILES["fileToUpload"]["name"] != "")
    >         {
    >             $target_dir = "/pics/";
    >             $target_file = 'Image_'.basename($_FILES["fileToUpload"]["name"]);
    >     
    >             $uploadOk = 1;
    >             $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
    >     
    >         // Check if image file is a actual image or fake image
    >             $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    >     
    >             if ($check !== false) {
    >                 $msg['status'] = '1';
    >                 $msg['message'] = "File is an image - " . $check["mime"] . ".";
    >                 $uploadOk = 1;
    >             } else {
    >                 $msg['status'] = '0';
    >                 $msg['message'] = "File is not an image.";
    >                 $uploadOk = 0;
    >             }
    >     
    >         // Check if file already exists
    >             if (file_exists($target_file)) {
    >                 $msg['status'] = '0';
    >                 $msg['message'] = "Sorry, file already exists.";
    >                 $uploadOk = 0;
    >             }
    >         // Check file size
    >             if ($_FILES["fileToUpload"]["size"] > 5000000) {
    >                 $msg['status'] = '0';
    >                 $msg['message'] = "Sorry, your file is too large.";
    >                 $uploadOk = 0;
    >             }
    >         // Allow certain file formats
    >             if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
    >                 $msg['status'] = '0';
    >                 $msg['message'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    >                 $uploadOk = 0;
    >             }
    >     
    >         // Check if $uploadOk is set to 0 by an error
    >             if ($uploadOk == 0) {
    >                 $msg['uploadstatus'] = "Sorry, your file was not uploaded.";
    >         // if everything is ok, try to upload file
    >             } else {
    >                 $target_dir = "/pics/";
    >                 if (!file_exists($target_dir)) {
    >                     try {
    >                         mkdir($target_dir);
    >                     } catch (Exception $ex) {
    >                         die("error");
    >                     }
    >                 }
    >                 if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
    > $target_dir.$target_file)) {
    >                     $data['imageTitle'] = basename($_FILES["fileToUpload"]["name"]);
    >                     $data['imageLink'] = $target_file;
    >                     $data['memberId'] = 5;     
    >                         $msg['id'] = 5;
    >                         $msg['name'] = basename($_FILES["fileToUpload"]["name"]);
    >                         $msg['size'] = ($_FILES["fileToUpload"]["size"] / 1024) . "kb";
    >                         $msg['status'] = '1';
    >                         $msg['message'] = "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
    >                         $msg['uploadstatus'] = "file uploaded";
    >                         $msg['imagepath'] = $target_dir;
    >                   
    >                 } else {
    >                     $msg['status'] = '0';
    >                     $msg['message'] = "Sorry, there was an error uploading your file.";
    >                     $msg['uploadstatus'] = "Sorry, your file was not uploaded.";
    >                 }
    >     
    >             }
    >         }
    

    【讨论】:

    • 亲爱的@RishikRohan,我已经尝试了你的两种解决方案,但不幸的是它们都不适合我。您的代码输出两个错误。但我不会丢弃它,我会努力让它发挥作用。谢谢
    猜你喜欢
    • 2014-01-06
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 2012-04-22
    • 2022-01-25
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    相关资源
    最近更新 更多