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; width: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;
    }
}

 

posted @ 2020-10-21 17:55  FivePointOne  阅读(444)  评论(0编辑  收藏  举报