javaweb servlet 接收 +js回显预览 批量上传图片 - Go语言中文社区

javaweb servlet 接收 +js回显预览 批量上传图片


jsp 代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax_File_Uploader_Plugin_For_Jquery</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<!-- <script>
$(document).ready(function(){
    $("#upload").change(function(){
        $.post("${pageContext.request.contextPath }/Upjquery",{            
            url:"http://www.runoob.com"
        },
        function(data,status){
            alert("数据: n" + data + "n状态: " + status);
        });
    });
});
</script> -->
<script>
$(document).ready(function(){
    $("#upload").change(function(){
        $("form").submit();
    });
});
</script>
</head>

<body>
    <h1>选择图片后,点击按钮上传</h1>
    <form action='<c:url value="/Upjquery" />' method="post" target="mywin" enctype="multipart/form-data">
    <input type="text" size="45" name="name">
    <input type="file" name="imgfile" id="upload" multiple="multiple">
    <!--<button class="button">上传</button>
     <button class="submit">上传</button> -->
    </form>
    <br>
    <style>
        #div1 img{width:100px;}
    </style>
    <div id="div1">
    <img id="viewImg" src="">
    </div>
    
    <iframe name="mywin" frameborder="1" style="display:none;">
    
    
        
    </iframe>
</body>
</html>

 java 代码

package d2001;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.day1201.utils.CommonUtils;

public class Upjquery extends HttpServlet {
    
    /*
     * protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     * throws ServletException, IOException { req.setCharacterEncoding("utf-8");
     * resp.setContentType("text/html;charset=utf-8"); ServletInputStream in =
     * req.getInputStream(); String img = IOUtils.toString(in);
     * System.out.println(img); }
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
         * 上传三步
         * 相关类 DiskFileItemFactory
         * ServletFileUpload
         * FileItem
         * 1,创建工厂 DiskFileItemFactory factory = new DiskFileItemFtory();
         * 2创建解析器 ServletFileUpload sfu = new ServletFileUpload(factory);
         * 3,使用解析器来解析 request ,得到 FileItem集合 : List<FileItem> fileItem = sfu.parseRequest(request);
         * FileItem API 接口
         * 
         */
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        System.out.println(888);
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        try {
            List<FileItem> fileItem = sfu.parseRequest(req);
            FileItem f0 = fileItem.get(0);
            
            for(int i = 1; i<fileItem.size(); i++) {
                FileItem f1 = fileItem.get(i);
                System.out.println("普通表单项"+f0.getFieldName()+"="+f0.getString("utf-8"));
                System.out.println("文件表单项");
                System.out.println("Content-type:"+f1.getContentType());
                System.out.println("size:"+f1.getSize());
                System.out.println("fileName:"+f1.getName());
                //保存的路径,得到根路径
                String root =this.getServletContext().getRealPath("/user/images/");
                /*
                 * 生成层目录,得到文件名称,得到hashCode,转发成16进制,获取前二个字符用来生成目录
                 */
                String filename = f1.getName(); //获取上传的文件名称
                //处理文件名的绝对路径问题
                int index = filename.lastIndexOf("\");
                if(index != -1) {
                    filename = filename.substring(index+1);
                }
                //处理同名
                String savename = CommonUtils.unid()+".jpg";
                /*
                 * 1,得到hashcode
                 */
                int hcode = filename.hashCode();
                String hex = Integer.toHexString(hcode);//16进制
                /*
                 * 2,获取hex的前两个字母,与root链接在一起,生成一个完整的路径
                 */
                File dirFile = new File(root,hex.charAt(0)+"/"+hex.charAt(1));
                
                /*
                 * 3,创建目录链,如果目录文件存在就不创建 ,不存在就创建
                 */
                dirFile.mkdirs();
                /*
                 * 4,创建目标文件
                 */
                File destFile = new File(dirFile,savename);
                //保存文件                
                f1.write(destFile);            
                
                
                String imgadd="user\\images\\"+hex.charAt(0)+"\\"+hex.charAt(1)+"\\"+savename;
                System.out.println(imgadd);
                resp.getWriter().write("<img src='"+imgadd+"'>");
                resp.getWriter().write("<script type="text/javascript">"+
                            "console.log("88");"+
                            "viewImg=top.document.getElementById('viewImg');"+
                            "viewImg.src='"+imgadd+"';"+
                            ""+
                            "element = top.document.getElementById("div1");rn" + 
                            "img = document.createElement("img");rn" +                             
                            "img.src='"+imgadd+"'; rn" + 
                            
                            "element.appendChild(img);"+
                            ""+
                            ""+
                            
                        "</script>");
                
            }
            
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {            
            throw new RuntimeException(e);
        }
        
    }
    
}
 

程序执行结果 如图

 

没有做过多的限制,例如,限制图片上传大小,和数量,亲可以自己做一下!相互学习交流,请加QQ 156356969 , 我也喜欢结交有志同道合的好朋友!喜欢摄影和旅游!

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_41957098/article/details/89067033
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-08 14:48:26
  • 阅读 ( 688 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢