zoukankan      html  css  js  c++  java
  • JQuery的ajaxFileUpload的使用--实现ajax上传文件

    HTML代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link href="../css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
            <input type="file" id="file" name="file"/><br>
            <button id="uploadBtn" class="btn  btn-primary" type="button" >上传</button><br>
            <img src="../img/9.jpg" class="img-circle" style="height: 255px; 255px">
    </body>
    <script src="../js/jquery-1.7.1.min.js"></script>
    <!--想要使用ajaxFileUpload插件必须引入这个js-->
    <script src="../js/ajaxfileupload.js"></script>
    <script>
        $(()=>{
            $('#uploadBtn').click(function () {
                $.ajaxFileUpload({
                    url:'../uploadFile',
                    type:'post',
                    fileElementId: "file", //需要上传的文件域的ID,即<input type="file">的ID
                    dataType:'String',
                    success: function(result) {
                        alert(result);
                        $(".img-circle").attr("src","../upload/" + result);
    
                    }
                })
    
            })
        })
    </script>
    </html>

    后台servlet代码:

    @WebServlet(name = "UploadFileServlet",value = "/uploadFile")
    //必须加此注解 重要!
    @MultipartConfig
    public class UploadFileServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Part part = request.getPart("file");
            String header = part.getHeader("content-disposition");
            //获得上传文件名
            String path = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
            // 获取文件的真实路径
            String realPath = this.getServletContext().getRealPath("/upload");
            String newFileName = generateUploadFileName(getRealName(path));
            File file = new File(realPath);
            //文件夹不存在则创建
            if (!file.exists()) {
                file.mkdirs();
            }
    
            // 获取输入流
            InputStream inputStream = part.getInputStream();
            // 定义输出流
            FileOutputStream outputStream = new FileOutputStream(new File(file, newFileName));
    
            // 从输入流中读入数据并写到输出字节流中
            int len = -1;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
    
            // 关闭资源
            outputStream.close();
            inputStream.close();
    
            // 删除临时文件
            part.delete();
            //向服务器返回新文件名
            response.getWriter().print(newFileName);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    
        public static String getRealName(String path) {
            int index = path.lastIndexOf("\");
            if (index == -1) {
                index = path.lastIndexOf("/");
            }
            return path.substring(index + 1);
        }
        //传入旧文件名,获得新的文件名
        public static String generateUploadFileName(String name){
            String suffixName = name.substring(name.lastIndexOf("."));
            return System.currentTimeMillis() + "_" +(int)(Math.random() * 100000) +suffixName;
        }
    }
  • 相关阅读:
    Java多线程——volatile关键字、发布和逸出
    线程安全性的基础知识
    maven web不能创建src/main/java等文件等问题
    web环境中的spring MVC
    Spring AOP 概述
    golang统计出其中英文字母、空格、数字和其它字符的个数
    go语言求1到100之内的质数
    golang fmt占位符
    golang---map类型
    golang切片类型
  • 原文地址:https://www.cnblogs.com/FivePointOne/p/13853844.html
Copyright © 2011-2022 走看看