简体   繁体   English

html:如何将上传文件格式限制为纯文本

[英]html: how to restrict upload file format to plain text

I need to have a upload file functionality on my web page. 我需要在网页上具有上传文件功能。 I only want people to be able to choose .csv and plain text(.txt) file. 我只希望人们能够选择.csv和纯文本(.txt)文件。

<input type="file" accept=".csv,text/plain" >

I know the attribute accept may work. 我知道接受属性可能有效。 But there are two problems. 但是有两个问题。

  1. It doesn't work with Firefox or Safari 它不适用于Firefox或Safari
  2. csv works fine, but text seems not restricted. csv工作正常,但文本似乎不受限制。 I can upload .java file, .rtf file, .python file, etc.. 我可以上传.java文件,.rtf文件,.python文件等。

Anyone knows how to implement that ? 有人知道如何实现吗?

Be mindful that anything that you do on the client side, for example using the accept attribute in the input tag, can easily be ignored/overridden by the client. 请注意,您在客户端执行的任何操作(例如使用input标签中的accept属性)都可以被客户端轻易地忽略/覆盖。 So, if you really want to prevent files other than the types that you specify from being uploaded to your server, then you should do some sort of checking on the server side, in the script that your form posts to. 因此,如果您确实要阻止将指定类型以外的文件上传到服务器,则应在表单发布到的脚本中在服务器端进行某种检查。

如果您只想接受txt文件,请将您的接受从text / plain更改为accept=".csv,.txt"

$target="images/";  //path to upload
if( isset($_POST['submit']) ) //check if post is set
{
        if $_FILES['file']['type'] != 'text/plain'
        {  
             // error
         } else {
           //upload
             move_uploaded_file($_FILES['file']['tmp_name'], $target);
          }   

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM