如何在客户端使用jquery将正则表达式应用于文件的内容


How to apply a regex to the content of a file on client side using jquery?

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

<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来验证数据,如果它通过,执行文件的内容,否则发送错误消息->不会有点慢。是否有任何方法可以在客户端查看文件的内容并应用正则表达式来测试内容?

您正在调用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属性),但你不能使用JavaScript保存回或覆盖原始文件