简体   繁体   English

文件上传:检查文件格式,然后调用srvlet

[英]File Upload: Check for file format and then invoke srvlet

I have a JSP code for file upload. 我有一个用于文件上传的JSP代码。 I have given the servlet path in the action attribute of 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>

Now I want to check if the file uploaded is of the type '.xml' and then redicrect to 'testservlet', if not i want to stay on same page. 现在,我想检查上传的文件是否为“ .xml”类型,然后重新定向到“ testservlet”,如果不是,我想停留在同一页面上。 How should I do it? 我该怎么办?

With the help of simple js method you can check the extension of the file. 借助简单的js方法,您可以检查文件的扩展名。
On form submit call the js method & then using split get the extension if extension!="xml" return false which will not allow control to go to your servlet. 在表单提交时,调用js方法,然后使用split来获取扩展名,如果extension!=“ xml”返回false,这将不允许控件进入您的servlet。
Check the code 检查代码

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM