sur*_*raj 7 javascript jsp file-format file-upload
我给用户上传这样的文件的选项
<form action="#" onsubmit="return Checkfiles(this);">
<center><input type="file" id="filename">
<input type="submit" value="Go!"></center>
</form>
Run Code Online (Sandbox Code Playgroud)
当用户上传文件时,我使用以下 javascript 函数验证文件
<script type="text/javascript">
function Checkfiles()
{
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "pdf" )
{
return true;
}
else
{
alert("Upload pdf files only");
fup.focus();
return false;
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
一切都很好。
但我想通过其他方式验证文件,而不仅仅是通过其扩展名,
我将给出这样做的理由。我将一个图像文件重命名为 image.pdf,现在它是 pdf 格式,但无法打开。
所以我想以确切的方式验证 pdf 文件。除了通过扩展名之外,还有其他方法可以检查吗?
编辑
我想在服务器端使用 jsp 页面进行验证。那我应该怎么做呢?
提前致谢 :)
要在 javascript 上验证文件类型,有以下几种方法:
// Your way: getting the extension and checking it.
// I suggest this way instead of using indexOf:
var ext = fileName.split('.').reverse()[0]
// Splits by '.', reverse the array, and returns the first element
// Another way: checking the type of the file
if ( fup.files[0].type === 'application/pdf' ) {
console.log( 'It is validated!' )
}
Run Code Online (Sandbox Code Playgroud)
现场示例:http : //jsbin.com/akati3/2感谢/sf/answers/320692151/
但是,您真的应该像其他人所说的那样在服务器端验证这一点。
据我所知,检查pdf是否确实是pdf只能在服务器端完成。您可以尝试使用 IText 或类似的东西打开它;我敢打赌,当您尝试打开或修改除 PDF 之外的其他内容时,它会引发某种异常。
| 归档时间: |
|
| 查看次数: |
21084 次 |
| 最近记录: |