我有一个表单,其中用户输入一些数据并上传文件。我正在尝试找到一种方法,可以将正则表达式应用于文件的内容,如果失败,则会发出某种警告,指出无法上传文件,因为不允许在服务器端处理文件中的内容.
<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 验证数据,如果通过则执行文件的内容,否则发送错误 msg -> 会不会有点慢..有没有什么在客户端查看文件内容并应用正则表达式来测试内容的方法?
最佳答案
您正在调用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 保存回或者覆盖原来的文件
关于javascript - 如何使用 jquery 将正则表达式应用于客户端文件的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25006982/