首页 > 解决方案 > 使用 php 上传 .docx 文件

问题描述

如何使用 php 脚本上传 .doc 和 .docx?我的脚本在 pdf 和 txt 上运行良好,但对于 doc 和 docx 它没有上传。我只需要脚本来上传 pdf doc docx 和 txt。

下面是我的代码

session_start();

$targetfolder = "testupload/";

 $targetfolder = $targetfolder . basename( $_FILES['file']['name']) ;

 $ok=1;

$file_type=$_FILES['file']['type'];

if ($file_type=="application/pdf" || $file_type=="application/msword" || $file_type=="text/plain") {

 if(move_uploaded_file($_FILES['file']['tmp_name'], $targetfolder))

 {

 
  $_SESSION['message'] ="The file ". basename( $_FILES["file"]["name"]). " uploaded successfully.";
       header("location:lecsubmit?done") ;
    } 



 else {

   $_SESSION['message']= "Sorry, your file was not uploaded.";
    header("location:lecsubmit?error") ;

 }

}

else {

 
  $_SESSION['message']= "You may only upload PDFs, DOCXs, DOCs or TXT files..";
    header("location:lecsubmit?error") ;
}

标签: php

解决方案


您的if检查 mime 类型的语句不接受 docx 文件。

有关 MS Office 文件的 mime 类型列表,请参见此处。在您的情况下,您也需要允许application/vnd.openxmlformats-officedocument.wordprocessingml.document

我可以建议一个小的重构:

$allowedMimes = [
    'application/pdf',
    'application/msword',
    'text/plain',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
];

if (in_array($_FILES['file']['type'], $allowedMimes)) {
    // .. continue to upload
} else {
    // show supported file types message
}

推荐阅读