我创建了一个网页,我只想使用JavaScript上传文本文件,它运行正常。
使用以下JavaScript,检查上传文件是否为txt?
<script>
function checkExt() {
if(document.mainForm.myfile.value.lastIndexOf(".txt")==-1) {
alert("Please upload only .txt extention file");
return false;
}
}
</script>
<form name="mainForm">
<input type="file" name="myfile" onchange="checkExt();"/>
</form>
问题:如果我手动将.exe文件的扩展名更改为.txt,那么它也会被上传,因为我只检查文件的扩展名。所以我的问题是如何保护 exe文件( 手动更改为txt )以便上传。
我想停止上传exe文件,强制或手动更改或重命名的jar文件。
答案 0 :(得分:2)
您需要在后端代码上验证已修改的exe文件到txt。这是非常简单的代码。下面的程序是检查文件是否可执行,或者exe文件改为.txt扩展名。
这里我们可以读取文件验证意味着文件是否包含字节代码
import java.io.File;
import java.io.FileInputStream;
public class TestExecutableFile {
public static void main(String[] args) {
byte[] firstBytes = new byte[4];
try {
FileInputStream input = new FileInputStream(new File("[filepath]/[filename]"));
input.read(firstBytes);
// Checking file is executable
if (firstBytes[0] == 0x4d && firstBytes[1] == 0x5a) {
System.out.println("Executable File");
}else{
System.out.println("Non Executable File");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
在我看来,客户端验证扩展不会达到目的,你需要在服务器端进行MIME类型验证才能更好地解决问题。
参考。文章Using .NET, how can you find the mime type of a file based on the file signature not the extension
ROFLwTIME
答案 2 :(得分:0)
您只需要使用form.value
但form.files
获取文件。在那里你可以找到文件的这些属性:
{
lastModified: 1502265800000
lastModifiedDate: Wed Aug 09 2017 11:03:20 GMT+0300 (EEST) {}
name: "14ecdf0302f4bbc84cfbbf85b3b94013.jpg"
size: 463225
type: "image/jpeg"
}