0

为了让我在上传之前轻松浏览正确的文件,这是我想要完成的。怎么做?

看起来像这样

我的输入代码:表单内部有两个输入。并具有可能相似的文件名。提交按钮将触发“uploadnow”功能。

 <td>UPLOAD#1: AGL_001.txt <input type="file" name="upload1" id="upload1"></td>
 <td>UPLOAD#2: AGL_0001.txt <input type="file" name="upload2" id="upload2"></td>

function uploadnow(){
   $allowed_upload1 = ['AGL_001.txt']; // added
   $allowed_upload2 = ['AGL_0001.txt']; //added

    if(isset($_FILES['upload1']['name'])){
        //$errors= array();
        $file_name = $_FILES['upload1']['name'];
        $file_size =$_FILES['upload1']['size'];
        $file_tmp =$_FILES['upload1']['tmp_name'];
        $file_type=$_FILES['upload1']['type'];
        $file_ext=strtolower(end(explode('.',$_FILES['upload1']['name'])));
        //$img_loc = $file_name.'.'.$file_ext;


      if (in_array($file_name, $allowed_upload1)) {
        move_uploaded_file($file_tmp,"uploads/".$file_name);
      } else {
        $message = "Sorry, wrong filename on UPLOAD#1";
        echo "<script type='text/javascript'>alert('$message');</script>";
      }
    }

    if(isset($_FILES['upload2']['name'])){
        //$errors= array();
        $file_name = $_FILES['upload2']['name'];
        $file_size =$_FILES['upload2']['size'];
        $file_tmp =$_FILES['upload2']['tmp_name'];
        $file_type=$_FILES['upload2']['type'];
        $file_ext=strtolower(end(explode('.',$_FILES['upload2']['name'])));
        //$img_loc = $file_name.'.'.$file_ext;

      if (in_array($file_name, $allowed_upload2)) {
          move_uploaded_file($file_tmp,"uploads/".$file_name);
      } else {
          $message = "Sorry, wrong filename on UPLOAD#2";
          echo "<script type='text/javascript'>alert('$message');</script>";
      }
    }
}
4

1 回答 1

0

我相信您无法在客户端预设文件名,但您可以使用accept输入中的属性来限制接受的文件类型(认为很难预测所有 mime 类型.txt附带):

<input type="file" accept="text/plain">

或更一般的

<input type="file" accept="text/*">

虽然这不是一个防弹解决方案,但您可能会破坏浏览器。

您可以实现一个 JavaScript 解决方案,该解决方案将侦听输入更改并验证文件名。

要在服务器端执行此操作,只需检查$_FILES[$input_name]['name'](或 $_FILES[$input_name][$index]['name'] 的值以获取具有multiple属性的文件输入)

$allowed_filenames = [
   'AGL_001.txt',
];

if(isset($_FILES['upload1']['name'])){
    //$errors= array();
    $file_name = $_FILES['upload1']['name'];
    $file_size =$_FILES['upload1']['size'];
    $file_tmp =$_FILES['upload1']['tmp_name'];
    $file_type=$_FILES['upload1']['type'];
    $file_ext=strtolower(end(explode('.',$_FILES['upload1']['name'])));
    //$img_loc = $file_name.'.'.$file_ext;

    if (in_array($file_name, $allowed_filenames)) {
        move_uploaded_file($file_tmp,"uploads/".$file_name);
    } else {
        // log an error
    }
}
于 2016-05-27T07:42:35.343 回答