多图预览上传 前后端 java jquery tomcat

news/2024/7/10 23:00:52 标签: java, js, tomcat, html, jquery

多图预览上传 前后端 html" title=java>java jquery html" title=tomcat>tomcat

  • 效果预览
    • 页面
    • 保存到硬盘
    • 数据库保存
  • 码代码
    • 前端
      • picture.html" title=js>jsp
      • html" title=js>js
      • css
    • 后端
      • controller
      • service
  • 附录-Servlet和JSTL依赖

示例环境:

环境版本
html" title=java>java1.8 +
html" title=tomcat>tomcat8.5
jquery3.3.1

效果预览

页面

你好! 这是你第一次使用 **Markdown编辑器** 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。

保存到硬盘

在这里插入图片描述

数据库保存

在这里插入图片描述

码代码

前端

html" title=js>jsp_24">picture.html" title=js>jsp

html"><%@ page contentType="text/html;charset=UTF-8" language="html" title=java>java" %>

<%@ taglib uri="http://html" title=java>java.sun.com/html" title=js>jsp/html" title=js>jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://html" title=java>java.sun.com/html" title=js>jsp/html" title=js>jstl/core" prefix="c" %>
<%@ taglib uri="http://html" title=java>java.sun.com/html" title=js>jsp/html" title=js>jstl/functions" prefix="fn" %>

<html>
<head>
    <title>维护照片</title>

    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.html" title=js>js"
            type="application/html" title=java>javascript">html" title=java>javascript"></script>

</head>
<body>
<div class="imgFile">

    <c:forEach items="${employee}" var="e">

        <div class="imgDiv"><img id="img卡片" src="${e.name}">
            <span><i class="imgRem">×</i></span>
        </div>
    </c:forEach>

    <label>
        <span></span>
        <input type="file" class="file">
    </label>

</div>

<input class="dm-bt1" type="button" value="保存图片"></input>

</body>

</html>

html" title=js>js_66">html" title=js>js

html" title=java>javascript"><script type="text/html" title=java>javascript">
    var imgFile = [];
    $(".file").change(function () {
        //获取图片信息
        var fileLise = $(this)[0].files;
        var fileLength = fileLise.length;
        //然后循环 生成html 插入页面上 最后就赋值给img
        for (var i = 0; i < fileLength; i++) {
            var imgDiv = '<div class="imgDiv"><img id="img' + fileLise[i].name + '"><span><i class="imgRem">×</i></span></div>';
            $(".imgFile").prepend(imgDiv);
            var imgName = document.getElementById("img" + fileLise[i].name);
            if (fileLise && fileLise[i]) {
                var file = new FileReader();
                file.readAsDataURL(fileLise[i]);
                file.onload = function () {
                    console.log(this.result);
                    imgFile.push(this.result);
                    imgName.src = this.result
                }
            }
        }
    });
    $(".imgFile").on("click", ".imgRem", function () {
        $(this).parents(".imgDiv").remove();
    });
    var list = [];
    $(".dm-bt1").click(function () {

        alert("dm-bt1 click");


        for (var i = 0; i < imgFile.length; i++) {
            console.log(imgFile[i]);
            var this_obj = {
                "picture": imgFile[i]
            };
            list.push(this_obj)
        }

        let html" title=js>jsonStr = JSON.stringify(list);

        $.ajax({
            type: "POST",
            async: false,
            url: "picturesSave.do",
            dataType: "html" title=js>json",
            data: {
                files: html" title=js>jsonStr,
                id: 1
            },
            success: function (data) {
                // if (data.isSucc == "T") {
                var gsrhtml = "";
                alert("保存完成");
                // } else {
                //     ErrorProcess(data.result);
                // }
            }
        })


    });


</script>

css

<style>
    .imgFile {
        width: 500px;
        border: 1px solid #dbdbdb;
        display: flow-root
    }

    @supports (display:flow-root) {
        .imgFile {
            display: flow-root;
        }
    }

    .imgFile label input {
        display: none
    }

    .imgFile label span {
        width: 100px;
        height: 100px;
        display: inline-block;
        border: 1px solid #999999;
        margin: 16px;
        position: relative
    }

    .imgFile label span:after {
        width: 60%;
        height: 1px;
        background: #dbdbdb;
        content: "";
        display: inline-block;
        position: absolute;
        top: 50%;
        left: calc(50% - 30%)
    }

    .imgFile label span:before {
        width: 1px;
        height: 60%;
        background: #dbdbdb;
        content: "";
        display: inline-block;
        position: absolute;
        left: 50%;
        top: calc(50% - 30%)
    }

    .imgFile .imgDiv {
        width: 100px;
        height: 100px;
        border: 1px solid #999999;
        margin: 16px;
        position: relative;
        float: left
    }

    .imgFile .imgDiv img {
        width: 100%;
        height: 100%;
    }

    .imgFile .imgDiv span {
        width: 100%;
        height: 20%;
        color: white;
        display: none;
        background: rgba(0, 0, 0, 0.38);
        position: absolute;
        top: 0;
        left: 0;
        right: 0
    }

    .imgFile .imgDiv i {
        font-style: inherit;
        float: right;
        cursor: pointer;
        margin-right: 5px;
        line-height: 100%;
        font-size: 20px
    }

    .imgFile .imgDiv:hover > span {
        display: block
    }

</style>

后端

controller

html" title=java>java">    //  返回图片视图
    @RequestMapping(value = "list"  , method = RequestMethod.GET)
    public ModelAndView list(){

        List<Employee> vo = employeeService.findAll();


        ModelAndView modelAndView = new ModelAndView("picture");
        modelAndView.addObject("employee", vo);
        return modelAndView;
    }

    /**
     * 保存图片
     * @param request
     * @param id
     * @param files
     * @return
     */
    @ResponseBody
    @RequestMapping("picturesSave")
    public String picturesSave(HttpServletRequest request, @RequestParam Integer id , String files ){
        JSONArray fileJsonArray = JSON.parseArray(files);

        employeeService.modifyEmployeePicture(id, fileJsonArray,request);

        return "redirect:list";
    }

service

html" title=java>java">    @Override
    public boolean modifyEmployeePicture(Integer id, JSONArray fileJsonArray, HttpServletRequest request) {

        String pictureDirPathStr = getTomcatWebAppsDirPath("pictureDirPath");

        for (int i = 0; i < fileJsonArray.size(); i++) {
            JSONObject html" title=js>jsonData = fileJsonArray.getJSONObject(i);

            String pictureName = generateImage(html" title=js>jsonData.getString("picture"), pictureDirPathStr);

//            获取request的请求域名+applicationContextPath
            String pictureUriPrefix = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();

            pictureUriPrefix  += "/";
            pictureUriPrefix += "pictureDirPath/";

            Employee newEmp = new Employee();
            newEmp.setName(pictureUriPrefix + pictureName);

            employeeDao.addOne(newEmp);
        }

        return true;
    }


    /**
     * 获取Tomcat环境下webapps目录中的某个子目录在磁盘上的全路径
     * @param webappsDirPath
     * @return
     */
    public String getTomcatWebAppsDirPath(String webappsDirPath) {
        String dirPath = new String();
        String courseFile;

        try {
            File directory = new File("");//参数为空

            courseFile = directory.getCanonicalPath(); // 获取到当前项目web容器的启动目录 (Tomcat下为html" title=tomcat>tomcat/bin
//                准备把图片保存到html" title=tomcat>tomcat/webapps下的某个目录下:需要对取到的路径字符串做剪切拼接
            if ("\\bin".equals(courseFile.substring(courseFile.length() - 4, courseFile.length())) || "/bin".equals(courseFile.substring(courseFile.length() - 4, courseFile.length()))) {
                dirPath = (courseFile.substring(0, courseFile.length() - 4) ); ;
            }

            dirPath += courseFile +  "/webapps/";

            dirPath += webappsDirPath+"/";

            log.warn("保存图片目录为:"+dirPath);
            System.out.println("保存图片目录为:"+dirPath);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return dirPath;
    }


    /**
     * base64字符串转化成图片
     * 返回保存的文件名字
     * 暂时支持image/jpeg格式
     */
    public static String generateImage(String imgStr , String directoryPath)
    {  //对字节数组字符串进行Base64解码并生成图片


        if (imgStr == null) //图像数据为空
            return null;
        /**
         * 示例只对jpg格式图片做了支持,对应的png格式也要这么做,文章篇幅有限自行处理吧
         */
        imgStr = imgStr.replaceAll("data:image/jpeg;base64,", "");
        String imgFilePathShort = new String();
        try
        {
            //Base64解码 html" title=java>java 1.8  html" title=java>java.util
            byte[] b = Base64.getDecoder().decode(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片名字
            imgFilePathShort = ""+new Date().getTime() + RandomUtils.nextInt() + ".jpg";  // 文件的名字

            String imgFilePath = directoryPath+imgFilePathShort;//新生成的图片 , 文件在磁盘上的全路径

            File newFile = new File(imgFilePath);

            if (!newFile.exists()) {
                newFile.createNewFile();
            }


            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return imgFilePathShort;
        }
        catch (Exception e){
            log.error("保存图片异常",e);
        }

        return null;
    }


附录-Servlet和JSTL依赖

        <!-- https://mvnrepository.com/artifact/html" title=java>javax.servlet.html" title=js>jsp.html" title=js>jstl/html" title=js>jstl -->
        <dependency>
            <groupId>html" title=java>javax.servlet</groupId>
            <artifactId>html" title=js>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/taglibs/standard -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl -->
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
        </dependency>

http://www.niftyadmin.cn/n/1307416.html

相关文章

图片的上传 下载 js html file 打包下载 .zip

记得以前做网站时&#xff0c;曾经需要实现一个图片上传到服务器前&#xff0c;先预览的功能。当时用html的<input type"file"/>标签一直实现不了&#xff0c;最后舍弃了这个标签&#xff0c;使用了其他方式来实现了这个功能。 今天无意发现了一个知识点&#…

Flex中AdvancedDataGrid的用法

1、AdvancedDataGrid实现双表头表格 &#xff08;1&#xff09;源码 AdvanceGrid.mxml <?xml version"1.0" encoding"utf-8"?> <s:Application xmlns:fx"http://ns.adobe.com/mxml/2009" xmlns:s"library://ns.adobe.com/flex…

Google Guava Retry 优雅的重试方案

Google Guava Retry 优雅的重试方案前言使用场景什么场景不适合重试了解幂等性一、Guava Retry是什么&#xff1f;与Spring retry比较二、使用步骤1.引入库2.码代码可以在判断重试条件里写Lambda表达式需要拿到最终运行的返回时总结导读前言 使用场景 当需要两个或者多个组件…

Flex中的HDividedBox和VDividedBox的比较

1、HDividedBox &#xff08;1&#xff09;源码 HVD.mxml&#xff1a; <?xml version"1.0" encoding"utf-8"?> <s:Application xmlns:fx"http://ns.adobe.com/mxml/2009" xmlns:s"library://ns.adobe.com/flex/spark" xm…

centos部署janus -(CentOS 7.6安装janus v0.10.10)

Janus系列文章 CentOS 7.6 部署前言一、Janus是什么&#xff1f;二、安装步骤1.安装依赖包2.安装gcc版本73.安装python34.安装ICE库5.安装SRTP库6.安装cmake37.安装data-channel支持8.安装WebSocket库9.安装libmicrohttpd10.安装janus-gateway生成配置文件11.试一下安装OK不总结…

centos部署janus 系列文章二 janus配置和管理

centos部署janus -janus配置和管理 前言一、配置1.环境和资料准备2.Tengine 反向代理Janus服务器2.1.Tengine 下载安装2.1.2 Tengine 配置2.1.3 验证Tengine配置3.部署demo4.配置Janus4.1.给Janus配置ICE&#xff08;turn、stun&#xff09;4.2.启用管理端点4.启动Janus验证配置…

分页java

引入分页的依赖 <!-- 分页拦截器 --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>4.1.6</version></dependency>分页的拦截器 package com.wkxhotel.web.waiter…