图片上传(支持拖拽上传)及列表图片预览

要注意的是图片路径

先看效果图:

下面是代码啦:

前端ftl

index:

<#assign base=request.contextPath/>
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
    <base id="base" href="${base}">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>图片资源管理</title>
<#include "${base}/common/head.ftl"/>
</head>
<body>
<div id="main">
    <div id="toolbar">
        <shiro:hasPermission name="upms:system:create"><a class="waves-effect waves-button" href="${base}/cebs/imags/add"><i class="zmdi zmdi-plus"></i> 添加图片</a></shiro:hasPermission>
        <shiro:hasPermission name="upms:system:delete"><a class="waves-effect waves-button" href="javascript:;" onclick="deleteAction()"><i class="zmdi zmdi-close"></i> 批量删除</a></shiro:hasPermission>
    </div>
    <!--搜索-->
    <form id="search-form" class="form-inline">
        <div class="input-group">
            <input type="text" id="keyword" class="form-control" placeholder="请输入图片名称"/>
            <div class="input-group-btn">
                <button type="button" class="btn btn-default" id="searchbtn"><span class="glyphicon glyphicon-search"></span></button>
            </div>
        </div>
    </form>
    <table id="table"></table>
</div>
<#include "${base}/common/footer.ftl"/>
<script>
    var $table = $('#table');
    //模糊搜索加载页面
    $('#searchbtn').click(function () {
        var keyword = $("#keyword").val();
        // bootstrap table初始化
        $table.bootstrapTable('destroy');
        initTableHeight();
        $table.bootstrapTable({
            url: '${base}/cebs/imags?keyword='+keyword,
            height: $(window).height()-60,
            striped: true,
            showRefresh: true,
            showColumns: true,
            minimumCountColumns: 2,
            clickToSelect: true,
            detailView: true,
            detailFormatter:function(index,row){
                var str = "";
                str+= "<div>";
                str+= "<label class='form-control' style='border:0px;'>图 片 名 称:";
                if(row.name==undefined||row.name==""){
                    str+= "-";
                }else{
                    str+=row.name;
                }
                str+="</label>";
                str+= "<label class='form-control' style='border:0px;'>图片预览:";
                if(row.imagepath==undefined){
                    str+= "-";
                }else{
                    str+="<img style='height:30px;'  src='"+row.imagepath+"'/>";
                }
                str+="</label>"
                str+= "<label class='form-control' style='border:0px;'>上 传 用 户:";
                if(row.uploaduser==undefined||row.uploaduser==""){
                    str+="-";
                }else{
                    str+=row.uploaduser;
                }
                str+="</label>";

                str+= "<label class='form-control' style='border:0px;'>上 传 时 间:";
                if(row.uploadtime==undefined){
                    str+= "-";
                }else{
                    str+=timeFormatter(row.uploadtime,row,index);
                }
                str+="</label>";
                str+= "<label class='form-control' style='border:0px;'>     URL:";
                if(row.url==undefined){
                    str+= "-";
                }else{
                    str+=row.url;
                }
                str+="</label>";
                str+= "<label class='form-control' style='border:0px;'>状          态:";
                if(row.upstatus==0){
                    str+="<span class='label label-default'>下线</span>"
                }else if(row.upstatus==1){
                    str+="<span class='label label-success'>上线</span>";
                }else{
                    str+= "-";
                }
                str+="</label>";
                str+= "</div>";
                return str;
            },
            pagination: true,
            paginationLoop: false,
            sidePagination: 'server',
            silentSort: false,
            smartDisplay: false,
            escape: true,
            idField: 'id',
            maintainSelected: true,
            toolbar: '#toolbar',
            uniqueId: "id",
            columns: [
                {field: 'ck', checkbox: true},
                {title: '序号', align: 'center',width:'50',formatter: 'orderFormatter'},
                {field: 'id',title: '图片编号',align: 'center',visible:false},
                {field: 'name', title: '图片名称', align: 'center'},
                {field: 'imagepath', title: '图片预览',align: 'center',formatter: 'imgFormatter'},
                {field: 'uploaduser', title: '上传用户', align: 'center'},
                {field: 'uploadtime', title: '上传时间',align: 'center',formatter: 'timeFormatter'},
                {field: 'url', title: 'URL',align: 'center'},
                {field: 'upstatus', title: '状态', align: 'center', formatter: 'statusFormatter'},
                {field: 'action', title: '操作', align: 'center', formatter: 'actionFormatter',width:'100'}
            ]
        });
    });

    //加载页面
    $(function() {
       // initTableHeight();
        $table.bootstrapTable({
            url: '${base}/cebs/imags',
            height: $(window).height()-60,
            striped: true,
            showRefresh: true,
            showColumns: true,
            minimumCountColumns: 2,
            clickToSelect: true,
            detailView: true,
            detailFormatter:function(index,row){
                var str = "";
                str+= "<div>";
                str+= "<label class='form-control' style='border:0px;'>图 片 名 称:";
                if(row.name==undefined||row.name==""){
                    str+= "-";
                }else{
                    str+=row.name;
                }
                str+="</label>";
                str+= "<label class='form-control' style='border:0px;'>图片预览:";
                if(row.imagepath==undefined){
                    str+= "-";
                }else{
                    str+="<img style='height:30px;'  src='"+row.imagepath+"'/>";
                }
                str+="</label>"
                str+= "<label class='form-control' style='border:0px;'>上 传 用 户:";
                if(row.uploaduser==undefined||row.uploaduser==""){
                    str+="-";
                }else{
                    str+=row.uploaduser;
                }
                str+="</label>";

                str+= "<label class='form-control' style='border:0px;'>上 传 时 间:";
                if(row.uploadtime==undefined){
                    str+= "-";
                }else{
                    str+=timeFormatter(row.uploadtime,row,index);
                }
                str+="</label>";
                str+= "<label class='form-control' style='border:0px;'>     URL:";
                if(row.url==undefined){
                    str+= "-";
                }else{
                    str+=row.url;
                }
                str+="</label>";
                /*str+= "<label class='form-control' style='border:0px;'>          URL:";
                if(row.price==undefined){
                    str+= "-";
                }else{
                    str+=row.price;
                }
                str+="</label>";*/
                str+= "<label class='form-control' style='border:0px;'>状          态:";
                if(row.upstatus==0){
                    str+="<span class='label label-default'>下线</span>"
                }else if(row.upstatus==1){
                    str+="<span class='label label-success'>上线</span>";
                }else{
                    str+= "-";
                }
                str+="</label>";
                str+= "</div>";
                return str;
            },
            pagination: true,
            paginationLoop: false,
            sidePagination: 'server',
            silentSort: false,
            smartDisplay: false,
            escape: true,
            idField: 'id',
            maintainSelected: true,
            toolbar: '#toolbar',
            uniqueId: "productid",
            columns: [
                {field: 'ck', checkbox: true},
                {title: '序号', align: 'center',width:'50',formatter: 'orderFormatter'},
                {field: 'id',title: '图片编号',align: 'center',visible:false},
                {field: 'name', title: '图片名称', align: 'center'},
                {field: 'imagepath', title: '图片预览',align: 'center',formatter: 'imgFormatter'},
                {field: 'uploaduser', title: '上传用户', align: 'center'},
                {field: 'uploadtime', title: '上传时间',align: 'center',formatter: 'timeFormatter'},
                {field: 'url', title: 'URL',align: 'center'},
                {field: 'upstatus', title: '状态', align: 'center', formatter: 'statusFormatter'},
                {field: 'action', title: '操作', align: 'center', formatter: 'actionFormatter',width:'100'}
            ]
        });
    });

    //给窗口添加resize()监听事件
   /* function initTableHeight(){
        $(window).resize(function(){
            $table.bootstrapTable("resetView",{
                height:$(window).height()-60
            })
        });
    }*/
    //格式化序号
    function orderFormatter(value, row, index) {
        var pageSize = $('#table').bootstrapTable('getOptions').pageSize;
        var pageNumber = $('#table').bootstrapTable('getOptions').pageNumber;
        return pageSize * (pageNumber - 1) + index + 1;
    }
    // 格式化时间
    function timeFormatter(value, row, index) {
        var date = new Date(value);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
        Y = date.getFullYear();
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1);
        D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
        m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
        s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
        return Y+"-"+M+"-"+D+" "+h+":"+m+":"+s;
    };
    // 格式化操作按钮
    function actionFormatter(value, row, index) {
        return [
            "<a class=\"update\" href=\"javascript:;\" onclick=\"updateAction('"+row.id+"')\" data-toggle=\"tooltip\" title=\"编辑\"><i class=\"glyphicon glyphicon-edit\"></i></a>  ",
            "<a class=\"delete\" href=\"javascript:;\" onclick=\"deleteAction('"+row.id+"')\" data-toggle=\"tooltip\" title=\"删除\"><i class=\"glyphicon glyphicon-remove\"></i></a>  ",

        ].join('');
    }
    // 格式化状态
    function statusFormatter(value, row, index) {
        if (value == 1) {
            return '<span class="label label-success">上线</span>';
        } else {
            return '<span class="label label-default">下线</span>';
        }
    }
    // 格式化预览图
    function imgFormatter(value, row, index) {
        if (value!=null){
            return '<img style="height:30px;"  src="'+value+'" />';
        }
    }

    // 编辑图片信息
    function updateAction(id) {
        window.location.href="${base}/cebs/imags/edit/"+id;
    }
    // 删除图片()
    var deleteDialog;
    function deleteAction(id) {
        if (id!=null){
            deleteDialog = $.confirm({
                type: 'red',
                animationSpeed: 300,
                title: false,
                content: '确认删除该图片信息吗?',
                buttons: {
                    confirm: {
                        text: '确认',
                        btnClass: 'waves-effect waves-button',
                        action: function () {
                            var ids = new Array();
                            for (var i in rows) {
                                ids.push(rows[i].productid);
                            }
                            $.ajax({
                                type: 'delete',
                                url: '${base}/cebs/imags/' + id,
                                success: function(result) {
                                    if (result.code != 1) {
                                        if (result.data instanceof Array) {
                                            $.each(result.data, function(index, value) {
                                                $.confirm({
                                                    theme: 'dark',
                                                    animation: 'rotateX',
                                                    closeAnimation: 'rotateX',
                                                    title: false,
                                                    content: value.errorMsg,
                                                    buttons: {
                                                        confirm: {
                                                            text: '确认',
                                                            btnClass: 'waves-effect waves-button waves-light'
                                                        }
                                                    }
                                                });
                                            });
                                        } else {
                                            $.confirm({
                                                theme: 'dark',
                                                animation: 'rotateX',
                                                closeAnimation: 'rotateX',
                                                title: false,
                                                content: result.data.errorMsg,
                                                buttons: {
                                                    confirm: {
                                                        text: '确认',
                                                        btnClass: 'waves-effect waves-button waves-light'
                                                    }
                                                }
                                            });
                                        }
                                    } else {
                                        deleteDialog.close();
                                        $table.bootstrapTable('refresh');
                                    }
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    $.confirm({
                                        theme: 'dark',
                                        animation: 'rotateX',
                                        closeAnimation: 'rotateX',
                                        title: false,
                                        content: textStatus,
                                        buttons: {
                                            confirm: {
                                                text: '确认',
                                                btnClass: 'waves-effect waves-button waves-light'
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    },
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        }else{
            var rows = $table.bootstrapTable('getSelections');
            if (rows.length == 0) {
                $.confirm({
                    title: false,
                    content: '请至少选择一条记录!',
                    autoClose: 'cancel|3000',
                    backgroundDismiss: true,
                    buttons: {
                        cancel: {
                            text: '取消',
                            btnClass: 'waves-effect waves-button'
                        }
                    }
                });
            } else {
                deleteDialog = $.confirm({
                    type: 'red',
                    animationSpeed: 300,
                    title: false,
                    content: '确认删除该图片信息吗?',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'waves-effect waves-button',
                            action: function () {
                                var ids = new Array();
                                for (var i in rows) {
                                    ids.push(rows[i].id);
                                }
                                $.ajax({
                                    type: 'delete',
                                    url: '${base}/cebs/imags/' + ids.join("-"),
                                    success: function(result) {
                                        if (result.code != 1) {
                                            if (result.data instanceof Array) {
                                                $.each(result.data, function(index, value) {
                                                    $.confirm({
                                                        theme: 'dark',
                                                        animation: 'rotateX',
                                                        closeAnimation: 'rotateX',
                                                        title: false,
                                                        content: value.errorMsg,
                                                        buttons: {
                                                            confirm: {
                                                                text: '确认',
                                                                btnClass: 'waves-effect waves-button waves-light'
                                                            }
                                                        }
                                                    });
                                                });
                                            } else {
                                                $.confirm({
                                                    theme: 'dark',
                                                    animation: 'rotateX',
                                                    closeAnimation: 'rotateX',
                                                    title: false,
                                                    content: result.data.errorMsg,
                                                    buttons: {
                                                        confirm: {
                                                            text: '确认',
                                                            btnClass: 'waves-effect waves-button waves-light'
                                                        }
                                                    }
                                                });
                                            }
                                        } else {
                                            deleteDialog.close();
                                            $table.bootstrapTable('refresh');
                                        }
                                    },
                                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                                        $.confirm({
                                            theme: 'dark',
                                            animation: 'rotateX',
                                            closeAnimation: 'rotateX',
                                            title: false,
                                            content: textStatus,
                                            buttons: {
                                                confirm: {
                                                    text: '确认',
                                                    btnClass: 'waves-effect waves-button waves-light'
                                                }
                                            }
                                        });
                                    }
                                });
                            }
                        },
                        cancel: {
                            text: '取消',
                            btnClass: 'waves-effect waves-button'
                        }
                    }
                });
            }
        }
    }
</script>
</body>
</html>

add页面:

<#assign base=request.contextPath/>
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
    <base id="base" href="${base}">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>图片管理</title>
<#include "${base}/common/head.ftl"/>
</head>
<body>
<div class="container kv-main">
    <div class="page-header">
        <h1>添加图片</h1>
    </div>
    <form enctype="multipart/form-data" method="post" id="uploadForm" action="/cebs/imags/add">
        <div class="input-group">
            <span class="input-group-addon">图片名称</span>
            <input type="text" class="form-control" placeholder="" name="name">
        </div>
        <br/>
        <div class="input-group" id="centerIpGroup">
            <label class="input-group-addon" id="basic-addon5">上传作者</label>
            <div class="input-group col-md-12 centerIp">
                <input type="text" class="form-control" id="ipInput" name="uploaduser">
                <#--<span class="input-group-btn">
                <button class="btn btn-info" type="button" data-toggle="tooltip" title="删除" id="delCenterIpGrp"><span class="glyphicon glyphicon-minus"></span></button>
                </span>-->
            </div>
            <#--<button class="btn btn-info" type="button" data-toggle="tooltip" title="新增" id="addCenterIpGrpBtn" onclick="addCenterIpGrp(this)"><span class="glyphicon glyphicon-plus"></span></button>-->
        </div>
        <br/>
        <br/>
        <div class="form-group">
            <span class="input-group-addon" style="border-radius: 4px;padding: 6px 12px; ">图片预览</span>
            <div class="file-loading">
                <input id="fileImage" type="file" multiple class="file" data-overwrite-initial="false" data-min-file-count="1" name="fileImage">
            </div>
        </div>
        <br/>
        <br/>
        <div>
            <label class="radio-inline">
                <input type="radio" name="upstatus" id="optionsRadios3" value="1" checked> 上线
            </label>
            <label class="radio-inline">
                <input type="radio" name="upstatus" id="optionsRadios4"  value="0"> 下线
            </label>
        </div>
        <br/>
        <div class="input-group">
            <span class="input-group-addon">URL</span>
            <input type="text" class="form-control" placeholder="" name="url">
        </div>
        <br/>
        <div class="col-lg-pull-8  pull-right">
            <input type="submit" class="btn btn-primary" value="确认"/>
            <button type="button" class="btn btn-primary" onclick="javascript:window.history.back(-1);">返回</button>
        </div>
        <br/><br/><br/><br/><br/><br/>
    </form>
</div>
</body>
<#include "${base}/common/footer.ftl"/>
<script>
    //添加图片描述输入框项
    function addCenterIpGrp(obj){
        html = '<div class="input-group col-md-12 centerIp">'+
                '<input type="text" class="form-control" id="ipInput" name="description">'+
                '<span class="input-group-btn">'+
                '<button class="btn btn-info" type="button" data-toggle="tooltip" title="删除" id="delCenterIpGrp"><span class="glyphicon glyphicon-minus"></span></button>'+
                '</span>'+
                '</div>'
        obj.insertAdjacentHTML('beforebegin',html);
    }
    $(document).on('click','#delCenterIpGrp',function(){
        var el = this.parentNode.parentNode;
        var centerIp = $(this).parent().parent().find('#ipInput').val();
        if (centerIp==""){
            el.parentNode.removeChild(el);
            return;
        }
        alertify.confirm('您确定要删除选中的命令?',
                function(e){
                    if(e){ el.parentNode.removeChild(el)}})})
    //编辑图片
    $("#fileImage").fileinput({
        language : 'zh',
        uploadUrl: '#', // you must set a valid URL here else you will get an error
        allowedFileExtensions: ['jpg', 'png', 'gif'],
        maxFileSize: 1000,
        maxFilesNum: 10,
        minFileCount: 1,
        maxFileCount: 1, //表示允许同时上传的最大文件个数
        dropZoneEnabled: true,//是否显示拖拽区域
        showUpload:false, //是否显示上传按钮
        showRemove :false, //是否显示移除按钮
        layoutTemplates :{
            // actionDelete:'', //去除上传预览的缩略图中的删除图标
            actionUpload:''//去除上传预览缩略图中的上传图片;
            // actionZoom:''   //去除上传预览缩略图中的查看详情预览的缩略图标。
        }
    });
    $("#file-2").fileinput({
        language : 'zh',
        uploadUrl: '#', // you must set a valid URL here else you will get an error
        allowedFileExtensions: ['jpg', 'png', 'gif'],
        overwriteInitial: false,
        maxFileSize: 1000,
        maxFilesNum: 10,
        minFileCount: 1,
        maxFileCount: 3, //表示允许同时上传的最大文件个数
        dropZoneEnabled: true,//是否显示拖拽区域
        showUpload:false, //是否显示上传按钮
        showRemove :false, //是否显示移除按钮
        layoutTemplates :{
            // actionDelete:'', //去除上传预览的缩略图中的删除图标
            actionUpload:''//去除上传预览缩略图中的上传图片;
            // actionZoom:''   //去除上传预览缩略图中的查看详情预览的缩略图标。
        }
    });
   
</script>
</html>


controller:

package com.ccdt.amos.cwms.controller;
import com.ccdt.amos.cwms.common.constant.CebsResult;
import com.ccdt.amos.cwms.common.constant.CebsResultConstant;
import com.ccdt.amos.cwms.common.util.FileUtil;
import com.ccdt.amos.cwms.common.util.UuidUtil;
import com.ccdt.amos.cwms.domain.CebsImags;
import com.ccdt.amos.cwms.service.CebsImagsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 
 * @Date:2018/6/13 18:17
 */

@Controller
public class CebsImagsController {
    @Autowired
    private CebsImagsService cebsImagsService;
    @Value("${my.uploadImgUrl}")
    private String uploadImgUrl;
    @Value("${my.fieldIp}")
    private String fieldIp;
    @Value("${my.imagsIp}")
    private String imagsIp;
    //系统首页
    @RequestMapping("indexs")
    public String showIndex(Model model) {

        return "index";
    }
    @RequestMapping(value = "/cebs/imags/index", method = RequestMethod.GET)
    public String index(Model model) {

        return "imags/index";
    }
    //图片资源管理
    @RequestMapping("/cebs/imags")
    @ResponseBody
    public Object getAll(CebsImags cebsImags,
                         @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                         @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                         @RequestParam(required = false, value = "keyword") String keyword){

        List<CebsImags> rows = cebsImagsService.getAll(cebsImags, offset, limit,keyword);
        int total = cebsImagsService.count(cebsImags);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }
    //添加页面
    @RequestMapping(value = "/cebs/imags/add", method = RequestMethod.GET)
    public String add(Model model) {

        return "imags/add";
    }
    //添加图片
    @RequestMapping(value = "/cebs/imags/add", method = RequestMethod.POST)
    public Object add(CebsImags cebsImags, HttpServletRequest request) {
        String name=cebsImags.getName();
        if (StringUtils.isNotEmpty(name)){
            name=name.replaceAll(",",";");
        }
        cebsImags.setName(name);
        /*String user=cebsImags.getUploaduser();
        if (StringUtils.isNotEmpty(user)){
            user=user.replaceAll(",",";");
        }
        cebsImags.setUploaduser(user);*/
        String state=cebsImags.getUpstatus();
        cebsImags.setUpstatus(state);
        Timestamp time = new Timestamp(System.currentTimeMillis());
        cebsImags.setUploadtime(time);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        MultiValueMap<String, MultipartFile> multiparMap = multipartRequest.getMultiFileMap();
        try {
            for (String key : multiparMap.keySet()) {
                List<MultipartFile> multipartFileList = (List<MultipartFile>) multiparMap.get(key);
                for (int i=0;i<multipartFileList.size();i++) {
                    MultipartFile file=multipartFileList.get(i);
                    MultipartConfigFactory factory = new MultipartConfigFactory();
                    //文件最大限制
                    factory.setMaxFileSize("10240KB");
                    if (file.getSize()!=0){
                        //获取上传文件的原始名称
                        String originalFilename = file.getOriginalFilename();
                        //新图片名称
                        SimpleDateFormat formatterDate = new SimpleDateFormat("yyyyMMdd");
                        String str = formatterDate.format(new Date());
                        String fileName = UuidUtil.getShortUuid() + originalFilename.substring(originalFilename.lastIndexOf("."));
//                        String filePath = request.getSession().getServletContext().getRealPath("uploadfiles/imags/" + str + "/");
                        String filePath = request.getServletContext().getRealPath("/");
                        filePath += "uploadfiles/imags/" + str + "/";
                        FileUtil.uploadFile(file.getBytes(), filePath, fileName);
                        String imagePath= uploadImgUrl+"imags/"+str+"/"+fileName;
                        if(("fileImage").equals(key)){
                            cebsImags.setImagepath(imagePath);
                        }
                        if (("file").equals(key)){

                        }
                    }
                }
            }
            //添加图片
            cebsImagsService.addImag(cebsImags);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/cebs/imags/index";
    }
    //删除图片信息
    @RequestMapping(value = "/cebs/imags/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        String [] id= ids.split("-");
        if(null!=id&&id.length!=0){
            for (int i = 0; i < id.length; i++) {
                try {
                    //删除图片信息
                    cebsImagsService.deleteById(Integer.valueOf(id[i]));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return new CebsResult(CebsResultConstant.SUCCESS, 0);
    }
   //编辑图片信息页面
   @RequestMapping(value = "/cebs/imags/edit/{id}", method = RequestMethod.GET)
   public String edit(@PathVariable("id") int id, ModelMap modelMap) {
       CebsImags cebsImags = cebsImagsService.selectById(id);
       String [] desc=cebsImags.getName().split(";");
       List<String> desclist=new ArrayList<>();
       for (int i=0;i<desc.length;i++){
           desclist.add(desc[i]);
       }
       String img=cebsImags.getImagepath();
       if (StringUtils.isNotEmpty(img)){
           cebsImags.setImagepath(img.replace(imagsIp,fieldIp));
       }
       modelMap.put("desclist",desclist);
       modelMap.put("cebsImags", cebsImags);
       return "imags/edit";
   }

    //编辑图片信息
    @RequestMapping(value = "/cebs/imags/edit", method = RequestMethod.POST)
    public Object edit(CebsImags cebsImags, HttpServletRequest request) {
        String desc=cebsImags.getName().replaceAll(",",";");
        cebsImags.setName(desc);
        String state=cebsImags.getUpstatus();
        cebsImags.setUpstatus(state);
        //根据id查询原有图片信息
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        MultiValueMap<String, MultipartFile> multiparMap = multipartRequest.getMultiFileMap();
        try {
            for (String key : multiparMap.keySet()) {
                List<MultipartFile> multipartFileList = (List<MultipartFile>) multiparMap.get(key);
                for (int i=0;i<multipartFileList.size();i++) {
                    MultipartFile file=multipartFileList.get(i);
                    MultipartConfigFactory factory = new MultipartConfigFactory();
                    //文件最大限制
                    factory.setMaxFileSize("10240KB");
                    if (file.getSize()!=0){
                        //获取上传文件的原始名称
                        String originalFilename = file.getOriginalFilename();
                        //新图片名称
                        SimpleDateFormat formatterDate = new SimpleDateFormat("yyyyMMdd");
                        String str = formatterDate.format(new Date());
                        String fileName = UuidUtil.getShortUuid() + originalFilename.substring(originalFilename.lastIndexOf("."));
                        String filePath = request.getSession().getServletContext().getRealPath("uploadfiles/imags/" + str + "/");
                        FileUtil.uploadFile(file.getBytes(), filePath, fileName);
                        String imagePath=uploadImgUrl+"imags/"+str+"/"+fileName;
                        if(("fileImage").equals(key)) {
                            cebsImags.setImagepath(imagePath);
                            cebsImagsService.editCebsImags(cebsImags);
                        }
                    }else {
                        cebsImagsService.editCebsImags(cebsImags);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/cebs/imags/index";
    }

aplication.properties配置

##默认域名ip
my.fieldIp=IP地址
##图片管理图片展示替换ip
my.productIp=
my.imagsIp=
my.uploadImgUrl=http://IP地址:8081/uploadfiles/
在服务器图片存储路径这样写:
server.tomcat.basedir=/usr/local/etc/ccdt/image

要有一个配置工具类:

package com.ccdt.amos.cwms.common.util;

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;

/**
 * tomcat 配置
 * @Author: 
 * @Date: 2018/4/12 20:22.
 */
@Configuration
public class TomcatConfig {

    @Bean
    public EmbeddedServletContainerCustomizer createEmbeddedServletContainerCustomizer()
    {
        return new MyEmbeddedServletContainerCustomizer();
    }
    class MyEmbeddedServletContainerCustomizer implements EmbeddedServletContainerCustomizer {
        public void customize(ConfigurableEmbeddedServletContainer container) {
            TomcatEmbeddedServletContainerFactory tomcatFactory = (TomcatEmbeddedServletContainerFactory) container;
            String filepath="/usr/local/etc/ccdt/image";
            File file = new File(filepath);
            if(!file.exists()){
                file.mkdirs();
            }
            tomcatFactory.setDocumentRoot(file);

        }
    }
    }

fileutil:

package com.ccdt.amos.cwms.common.util;

import sun.misc.BASE64Decoder;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * @Author: 
 * @Date: 
 */
public class FileUtil {

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    /**
     * 通过BASE64Decoder解码,并生成图片
     * @param imgStr
     * @param imgPath
     * @return
     */
    public static  boolean imgBase64(String imgStr,String imgPath){
        // 对字节数组字符串进行Base64解码并生成图片
        if (imgStr==null){
            return  false;
        }else{
            try {
                //BASE64解码
                byte[] b=new BASE64Decoder().decodeBuffer(imgStr);
                for (int i = 0; i < b.length; ++i) {
                    if (b[i]<0){
                        //调整异常数据
                        b[i]+=256;
                    }
                }
                //生成JPEG图片
                OutputStream outputStream=new FileOutputStream(imgPath);
                outputStream.write(b);
                outputStream.flush();
                outputStream.close();
                return true;
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
    }
    /**
     * 删除单个文件
     * @param   filePath    被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            System.out.println("删掉了");
            flag = true;
        }
        return flag;
    }
//    /**
//     * 旋转图片为指定角度
//     *
//     * @param bufferedimage
//     *            目标图像
//     * @param degree
//     *            旋转角度
//     * @return
//     */
//    public static BufferedImage rotateImage(final BufferedImage bufferedimage,
//                                            final int degree) {
//        int w = bufferedimage.getWidth();
//        int h = bufferedimage.getHeight();
//        int type = bufferedimage.getColorModel().getTransparency();
//        BufferedImage img;
//        Graphics2D graphics2d;
//        (graphics2d = (img = new BufferedImage(w, h, type))
//                .createGraphics()).setRenderingHint(
//                RenderingHints.KEY_INTERPOLATION,
//                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
//        graphics2d.rotate(Math.toRadians(degree), w / 2, h / 2);
//        graphics2d.drawImage(bufferedimage, 0, 0, null);
//        graphics2d.dispose();
//        return img;
//    }



    public static BufferedImage rotateImage(BufferedImage src, int angel) {
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        // calculate the new image size
        Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(
                src_width, src_height)), angel);

        BufferedImage res = null;
        res = new BufferedImage(rect_des.width, rect_des.height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = res.createGraphics();
        //用于跟换背景色
        Graphics2D g3 = res.createGraphics();
        // transform
        g2.translate((rect_des.width - src_width) / 2,
                (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
        //设置画笔颜色为白色不设置怎为黑色
        g3.setColor(Color.WHITE);
        //填充背景色
        g3.fill(rect_des);
        g2.drawImage(src, null, null);
        return res;
    }

    public static Rectangle CalcRotatedSize(Rectangle src, int angel) {
        // if angel is greater than 90 degree, we need to do some conversion
        if (angel >= 90) {
            if(angel / 90 % 2 == 1){
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }

        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);

        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new Rectangle(new Dimension(des_width, des_height));
    }
}

getip工具类:

package com.ccdt.amos.cwms.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class GetIpSite {
    //获取ip地址,参数为("ip="+ip,"utf-8")
    public String getIpSite(String content, String encoding){
        String url = "http://ip.taobao.com/service/getIpInfo.php";
        String result = this.getResult(url,content,encoding);
        StringBuffer ipSite = new StringBuffer();
        if(StringUtils.isNotBlank(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            int code = (int)jsonObject.get("code");
            if(code == 0) {
                Map<String, String> res = (Map<String, String>) jsonObject.get("data");
                String country = res.get("country");
                String region = res.get("region");
                String city = res.get("city");
                if(StringUtils.isBlank(country) && StringUtils.isBlank(region) && StringUtils.isBlank(city)){
                    ipSite.append("获取ip地域失败...");
                }else {
                    if (!country.equals("XX") && StringUtils.isNotBlank(country)) {
                        ipSite.append(country + " ");
                    }
                    if (!region.equals("XX") && StringUtils.isNotBlank(region)) {
                        ipSite.append(region + " ");
                    }
                    if (!city.equals("XX") && StringUtils.isNotBlank(city)) {
                        ipSite.append(city);
                    }
                }
            }else{
                ipSite.append("获取ip地域失败...");
            }
        }
        return ipSite.toString();
    }
    private String getResult(String urlStr, String content, String encoding) {
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
            connection.setDoOutput(true);// 是否打开输出流 true|false
            connection.setDoInput(true);// 是否打开输入流true|false
            connection.setRequestMethod("GET");// 提交方法POST|GET
            connection.setUseCaches(false);// 是否缓存true|false
            connection.connect();// 打开连接端口
            DataOutputStream out = new DataOutputStream(connection
                    .getOutputStream());// 打开输出流往对端服务器写数据
            out.writeBytes(content);//往出写数据
            out.flush();// 刷新
            out.close();// 关闭输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
            // ,以BufferedReader流来读取
            StringBuffer buffer = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }
        return null;
    }
}

UUID工具类:

package com.ccdt.amos.cwms.common.util;

import java.util.UUID;

/**
 * @Author: 
 * @Date:2018/6/15 10:42
 */
public class UuidUtil {
    /**
     * @return  获取Uuid方法
     */
    public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z" };
    public static String getUuid() {
        String[] splits = UUID.randomUUID().toString().split("-");
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < splits.length; i++) {

            buffer.append(splits[i]);
        }
        return buffer.toString();
    }

    public static String getShortUuid() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();
    }


}

公共类:

package com.ccdt.amos.cwms.common.constant;
import com.ccdt.amos.cwms.common.base.BaseConstants;

public class CebsConstant extends BaseConstants {

    public static final String CIMS_TYPE = "cims.type";

}
package com.ccdt.amos.cwms.common.constant;
import com.ccdt.amos.cwms.common.base.BaseResult;
public class CebsResult extends BaseResult {

    public CebsResult(CebsResultConstant cimsResultConstant, Object data) {
        super(cimsResultConstant.getCode(), cimsResultConstant.getMessage(), data);
    }

}

package com.ccdt.amos.cwms.common.constant;

public enum CebsResultConstant {

    /**
     * 失败
     */
    FAILED(0, "failed"),

    /**
     * 成功
     */
    SUCCESS(1, "success"),

    /**
     * 无效长度
     */
    INVALID_LENGTH(10001, "Invalid length"),

    /**
     * 用户名不能为空
     */
    EMPTY_USERNAME(10101, "Username cannot be empty"),

    /**
     * 密码不能为空
     */
    EMPTY_PASSWORD(10102, "Password cannot be empty"),

    /**
     * 帐号不存在
     */
    INVALID_USERNAME(10103, "Account does not exist"),

    /**
     * 密码错误
     */
    INVALID_PASSWORD(10104, "Password error"),

    /**
     * 无效帐号
     */
    INVALID_ACCOUNT(10105, "Invalid account"),

    /**
     * 验证码不能为空
     */
    EMPTY_SMSCODE(10106, "SMSCODE cannot be empty"),

    /**
     * 验证码无效
     */
    INVALID_SMSCODE(10107, "Invalid SMSCODE");

    public int code;

    public String message;

    CebsResultConstant(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}
package com.ccdt.amos.cwms.common.constant;

public class Constants {
   public class MsgCode{
   public static final String EMPTY = "204";
   public static final String     ERROR = "500";
   public static final String     SUCCESS = "200";
   }
   
   public class MsgCodeText{
      public static final String SUCCESS = "操作成功";
      public static final String EMPTY = "参数缺失";
      public static final String     ERROR = "系统异常";
   }
}

base类:

package com.ccdt.amos.cwms.common.base;

/**
 * 统一返回结果类
 * Created by shuzheng on 2017/2/18.
 */
public class BaseResult {

    /**
     * 状态码:1成功,其他为失败
     */
    public int code;

    /**
     * 成功为success,其他为失败原因
     */
    public String message;

    /**
     * 数据结果集
     */
    public Object data;

    public BaseResult(int code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

}
package com.ccdt.amos.cwms.common.base;

public class BaseExample {
   protected boolean isPager;
    protected int offset;
    protected int limit;
    
   public boolean isPager() {
      return isPager;
   }
   public void setPager(boolean isPager) {
      this.isPager = isPager;
   }
   public int getOffset() {
      return offset;
   }
   public void setOffset(int offset) {
         this.offset = offset;
   }
   public int getLimit() {
      return limit;
   }
   public void setLimit(int limit) {
      this.limit = limit;
   }
}
package com.ccdt.amos.cwms.common.base;

public class BaseColumn {
    private String columnName;
    private String columnComment;

    public BaseColumn(String columnName, String columnComment) {
        this.columnName = columnName;
        this.columnComment = columnComment;
    }

    public String getColumnName() {
        return columnName;
    }

    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

    public String getColumnComment() {
        return columnComment;
    }

    public void setColumnComment(String columnComment) {
        this.columnComment = columnComment;
    }

    @Override
    public String toString() {
        return "BaseColumn{" +
                "columnName='" + columnName + '\'' +
                ", columnComment='" + columnComment + '\'' +
                '}';
    }
}














猜你喜欢

转载自blog.csdn.net/qq_41593567/article/details/80900635