在docx文件中上传错误,但能够以相同的代码上传pdf

时间:2018-09-28 10:49:36

标签: php file-upload

Am尝试上传docx文件格式,并且xlsx无法将文件移动到它抛出错误的位置。 这里的上传代码

/*     Upload Pdf  */
    if(isset($_FILES["file"]) && $_FILES["file"]["error"] == 0){
    $allowed = array('pdf' => "application/pdf",'doc' => "application/msword",'docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    $filename = $_FILES["file"]["name"];
    $filetype = $_FILES["file"]["type"];
    $filesize = $_FILES["file"]["size"];

    // Verify file extension
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");

    // Verify file size - 5MB maximum
    $maxsize = 5 * 1024 * 1024;
    if($filesize > $maxsize) die("Error: File size is larger than 5MB the allowed limit.");

    // Verify MYME type of the file
    if(in_array($filetype, $allowed)){
        // Check whether file exists before uploading it
        if(file_exists("../../upload/courses/pdf/" . $_FILES["file"]["name"])){
            unlink("../../upload/courses/pdf/" . $_FILES["file"]["name"]);

            $tmph = $_FILES["file"]["tmp_name"];
            $pathh = "../../upload/courses/pdf/" . $_FILES["file"]["name"];

            move_uploaded_file($tmph,$pathh );
        } else{
            $tmph = $_FILES["file"]["tmp_name"];
            $pathh = "../../upload/courses/pdf/" . $_FILES["file"]["name"];

            move_uploaded_file($tmph,$pathh );
            //echo "Your file was uploaded successfully.";

        } 
    } else{   echo "Error: There was a problem uploading your file. Please try again.";        }




} 
        $filepath =substr("../../upload/courses/pdf/" . $_FILES["file"]["name"],3);

       if($_FILES["file"]["size"] == 0 && $_FILES["file"]["error"] == 4){

        $file ='';
        }
        else{
            $file = ",file='".$filepath."'";
        }
  

链接move_uploaded_file()部分出错

使用相同的文件代码可以上传pdf文件,但会导致docx和xlsx文件格式错误。

1 个答案:

答案 0 :(得分:0)

在上面的部分中,我检查了带有打印文件类型的MIME,它使我得到了我需要使用的文件mimetype。  所以我改变了

$allowed = array('pdf' => "application/pdf",'doc' => "application/msword",'docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document');

收件人

$allowed = array('pdf' => "application/pdf",'doc' => "application/msword",'docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document','docx'=>'application/octet-stream');

就我而言,它与此匹配项'docx'=>'application/octet-stream'配合使用,万一出现错误,则意味着尝试通过回显检查或打印$_FILES["file"]["type"];