【问题标题】:How to apply a regex to the content of a file on client side using jquery?如何使用 jquery 将正则表达式应用于客户端文件的内容?
【发布时间】:2014-07-29 01:37:47
【问题描述】:

我有一个表单,其中用户来输入一些数据并上传文件。我正在尝试找到一种方法,可以将正则表达式应用于文件的内容,如果失败,则会发出某种警告,说无法上传文件,因为不允许在服务器端处理文件中的内容.

<div class="widget-body no-padding">

 <form action="exec.php" id="exec-python2"  method="post" enctype="multipart/form-data">
    <input type="hidden" name="job_name" value="run_sql">
    <input type="hidden" name="job_type" value="sql">
    <input type="hidden" name="job_status" value="active">
<fieldset>
   <section>
    <input type="file" name="file" id="file"/>
   </section>
   <div id="editor"></div>
</fieldset>     

我试过这样的东西,但这只是显示编码数据

$("#button2").click(function() {

    if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
        alert('The File APIs are not fully supported in this browser.');
        return;
    }   

    input = document.getElementById('file');

    if (!input) {
        alert("Um, couldn't find the fileinput element.");
    }
    else if (!input.files) {
        alert("This browser doesn't seem to support the `files` property of file inputs.");
    }
    else if (!input.files[0]) {
        alert("Please select a file before clicking 'Load'");               
    }
    else {
        file = input.files[0];
        fr = new FileReader();
        fr.onload = receivedText;
        //fr.readAsText(file);
        fr.readAsDataURL(file);
        alert('a)');
    }

});

function receivedText() {  
    alert('hello');         
   //result = fr.result;
   alert(fr.result);
} 

如果我尝试先在服务器上上传一个文件并使用 php 来验证数据,如果它通过了,则执行文件的内容,否则发送错误消息 -> 那不会有点慢.. 有没有在客户端查看文件内容并应用正则表达式来测试内容的方式?

【问题讨论】:

    标签: javascript php jquery regex


    【解决方案1】:

    您正在调用fr.readAsDataURL(file);,这是将您的文件转换为数据URL,因此“这只是显示编码数据”,您想要的功能是fr.readAsText,例如

    function readTextFile(blob, callback, encoding) {
        var fr = new FileReader();
        fr.addEventListener('load', function () {callback(this.result);});
        if (encoding)
            fr.readAsText(blob, encoding);
        else
            fr.readAsText(blob);
    }
    
    // using it
    readTextFile(input.files[0], function (text) {console.log(text);});
    

    DEMO(打开你的控制台)


    您可以更改内存中的文本,并且可以再次“下载”文件(请参阅download attribute),但您不能使用 JavaScript 保存回或者覆盖原文件

    【讨论】:

      猜你喜欢
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多