文件上传:检查文件格式,然后调用 servlet
File Upload: Check for file format and then invoke srvlet
我有一个 JSP 文件上传代码。我在form的action属性中给出了servlet路径。
<html>
<head>
<style>
body {
background-color: #CCCCFF;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Page</title>
</head>
<body>
<center>
<h1 align="center" >Status Of Metadata Components<br><br></h1>
<P> Upload the Package.xml File</P>
<form method="post" action="Testservlet"
enctype="multipart/form-data">
Select file to upload: <input type="file" name="file" size="60" /><br />
<br /> <input type="submit" value="Upload" />
</form>
</center>
</body>
</html>
现在我想检查上传的文件是否为 '.xml' 类型,然后重定向到 'testservlet',如果不是我想留在同一页面上。我应该怎么做?
借助简单的js方法,您可以检查文件的扩展名。
在表单提交上调用 js 方法,然后使用 split 获取扩展名 if extension!="xml" return false 这将不允许控制转到您的 servlet。
检查代码
<html>
<head>
<script>
function checkFile()
{
var name = document.getElementById("file").value;
var extension = name.split(".");
if(extension[1]!="xml")
{
alert("Incorrect file");
return false;
}
else
{
alert("Correct file");
return true;
}
}
</script>
</head>
<body>
<form action="TestServlet" method="post" onsubmit="return checkFile()">
Select file to upload: <input type="file" name="file" id="file" size="60" />
<br/><input type="submit" id="btnSubmit" value="Upload">
</form>
</body>
</html>
我有一个 JSP 文件上传代码。我在form的action属性中给出了servlet路径。
<html>
<head>
<style>
body {
background-color: #CCCCFF;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Page</title>
</head>
<body>
<center>
<h1 align="center" >Status Of Metadata Components<br><br></h1>
<P> Upload the Package.xml File</P>
<form method="post" action="Testservlet"
enctype="multipart/form-data">
Select file to upload: <input type="file" name="file" size="60" /><br />
<br /> <input type="submit" value="Upload" />
</form>
</center>
</body>
</html>
现在我想检查上传的文件是否为 '.xml' 类型,然后重定向到 'testservlet',如果不是我想留在同一页面上。我应该怎么做?
借助简单的js方法,您可以检查文件的扩展名。
在表单提交上调用 js 方法,然后使用 split 获取扩展名 if extension!="xml" return false 这将不允许控制转到您的 servlet。
检查代码
<html>
<head>
<script>
function checkFile()
{
var name = document.getElementById("file").value;
var extension = name.split(".");
if(extension[1]!="xml")
{
alert("Incorrect file");
return false;
}
else
{
alert("Correct file");
return true;
}
}
</script>
</head>
<body>
<form action="TestServlet" method="post" onsubmit="return checkFile()">
Select file to upload: <input type="file" name="file" id="file" size="60" />
<br/><input type="submit" id="btnSubmit" value="Upload">
</form>
</body>
</html>