使用Ajax和servlet上传图片并预览详解编程语言

前台代码如下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>图片上传 | cookie</title>
</head>
<body>
    file: <input type=”file” id=”images” name=”image” /><br><br>
    desc: <input type=”text” id=”desc” name=”desc” /><br><br>
    <input type=”button” value=”upload” onclick=”upload();”>
    <div class=”images”></div>
<script type=”text/javascript” src=”js/jquery-1.12.4.min.js”></script>
<script type=”text/javascript” src=”js/upload.js”></script>
<script type=”text/javascript”>
    function upload() {
        $.ajaxFileUpload({
            url : ‘upload.htm’,
            fileElementId : ‘images’,
            dataType : ‘json’,
            data : {desc : $(“#desc”).val()},
            success : function(data) {
                var html = $(“.images”).html();
                html += ‘<img width=”100″ height=”100″ src=”/HotelManager/upload/’ + data.url + ‘”>’
                $(“.images”).html(html);
            }
        })
        return false;
    }
</script>
</body>
</html>
java代码示例如下:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    String path = request.getServletContext().getRealPath(“/upload”);
    String name = null;
    try {
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if(item.isFormField()){
                System.out.println(item.getFieldName() + “: ” + item.getString());
            } else {
                name = item.getName();
                item.write(new File(path,name));
            }
        }
        PrintWriter out = response.getWriter();
        out.print(“{“);
        out.print(“url:/”” + name +”/””);
        out.print(“}”);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

使用Ajax和servlet上传图片并预览详解编程语言

转载请注明来源网站:blog.ytso.com谢谢!

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/14798.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论