上传具有特定文件名的文件

时间:2016-05-27 07:11:41

标签: php function file file-upload fileopendialog

让我在上传之前轻松浏览正确的文件,这就是我想要实现的目标。怎么做?

look like this

我的输入代码: 表格内部有两个输入。并且可能有类似的文件名。提交按钮将触发“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>";
      }
    }
}

1 个答案:

答案 0 :(得分:0)

我相信您无法在客户端预设文件名,但您可以在输入中约束带有accept属性的已接受文件类型(认为它很难预测所有mime类型{{ 1}}自带):

.txt

或更一般

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

虽然这不是一个防弹解决方案,但你可以搞砸浏览器。

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

要执行服务器端,只需检查<input type="file" accept="text/*">(或$ _FILES [$ input_name] [$ index] [&#39; name&#39;]的值,以获取{{1}的文件输入}属性)

$_FILES[$input_name]['name']