servlet 上传文件

java 

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part = req.getPart("file");
        String cd = part.getHeader("content-disposition");
        String filename=req.getParameter("filename");
        InputStream  is=part.getInputStream();
        File  file=new File("d:"+File.separatorChar, filename);
        FileOutputStream fos=new FileOutputStream(file);
        byte[] buff=new byte[1024*4];
        int len=0;
        while((len=is.read(buff))>0) {
            fos.write(buff, 0, len);
            fos.flush();
        }
        fos.close();
        is.close();
    }

js

<script src="./js/jquery-3.3.1.js"></script>

<script>
    $(function(){
        $("input[type='submit']").click(
                function(){
                    var filepath=$("input[type='file']").val();
                    var file=filepath.split("\\");
                    var filename=file[file.length-1];
                    $("input[type='hidden']").attr("value",filename);
                });
    });
</script>
</head>
<body>
    <h1>hello tomcat 123.....</h1></br>
    <form action="upfile" method="post"  enctype="multipart/form-data">

    <input type="file" name="file"/>
    <input type="hidden" name="filename"/>
    <input type="submit" value="submit" name="submit"/>
    
    </form>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/libing029/p/10718908.html