springboot+idea+bootstrap实现图片上传

下面写的这个是根据实际项目中的内容写的,你们看的时候稍微注意下哈。

1.导入相关js

fileinput插件下载地址:https://github.com/kartik-v/bootstrap-fileinput/releases

 <script type="application/javascript" src="/lib/js/jquery-3.1.1.js"></script>
    <script type="application/javascript" src="/lib/js/fileinput.js"></script>
    <script type="text/javascript"
            src="/lib/js/zh.js"></script>

2、添加按钮

 <input type="button" class="btn btn-primary" id="addBtn" value="添加"/>

3、创建添加按钮模态框

<!--添加操作模态框-->
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="myModalLabel1">新闻添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" action="" method="post">
                    <div class="item">
                        <h3>新闻添加</h3>
                    </div>
                    <div class="item">
                        新闻标题:
                        <input type="text" class="form-control" name="title" id="title-1"
                               placeholder="请输入标题"/><span
                            class="state1"></span></div>
                    <div class="item">
                        新闻内容:
                        <textarea class="form-control" name="content" id="content-1" rows="3"></textarea>
                        <span
                                class="state1"></span></div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">新闻图片</label>
                        <div class="col-sm-10">
                            <input type="file" name="imagepath" data-ref="url2"
                                   class="col-sm-10 myfile" value=""/> <input type="hidden"
                                                                              name="url2" id="imagepath-1" value="">
                        </div>
                    </div>


                    <div class="item">

                        <button type="button" id="addBtn1" class="btn btn-primary" data-dismiss="modal"><span
                                class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>保存
                        </button>
                        <button type="button" class="btn btn-default" data-dismiss="modal"><span
                                class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

5、上传图片相关js代码如下 ,我做的是异步上传,先上传存储在返回一个图片名称

    //上传图片操作
    $(".myfile").fileinput({
        uploadUrl: "/noticeManager/notice/uploadFile", //接受请求地址
        uploadAsync: true, //默认异步上传
        showUpload: false, //是否显示上传按钮,跟随文本框的那个
        showRemove: false, //显示移除按钮,跟随文本框的那个
        showCaption: true,//是否显示标题,就是那个文本框
        showPreview: true, //是否显示预览,不写默认为true
        dropZoneEnabled: false,//是否显示拖拽区域,默认不写为true,但是会占用很大区域
        //minImageWidth: 50, //图片的最小宽度
        //minImageHeight: 50,//图片的最小高度
        //maxImageWidth: 1000,//图片的最大宽度
        //maxImageHeight: 1000,//图片的最大高度
        //maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
        //minFileCount: 0,
        maxFileCount: 1, //表示允许同时上传的最大文件个数
        enctype: 'multipart/form-data',
        validateInitialCount: true,
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
        allowedFileTypes: ['image'],//配置允许文件上传的类型
        allowedPreviewTypes: ['image'],//配置所有的被预览文件类型
        allowedPreviewMimeTypes: ['jpg', 'png', 'gif'],//控制被预览的所有mime类型
        language: 'zh'
    })
    //异步上传返回结果处理
    $('.myfile').on('fileerror', function (event, data, msg) {

        console.log("fileerror");
        console.log(data);
    });
    //异步上传返回结果处理
    $(".myfile").on("fileuploaded", function (event, data, previewId, index) {
        console.log("fileuploaded");
        var ref = $(this).attr("data-ref");
        var aa = $("input[name='" + ref + "']").val(data.response.url);
        var jsonData = JSON.stringify(aa);// 转成JSON格式
        var result = $.parseJSON(jsonData);// 转成JSON对象
    });

    //上传前
    $('.myfile').on('filepreupload', function (event, data, previewId, index) {
        var form = data.form, mynewpic = data.mynewpic, extra = data.extra,
            response = data.response, reader = data.reader;
        console.log("文件正在上传。。。。");
    });

6、后台代码controller

 @RequestMapping("/uploadFile")
    @ResponseBody
    public Map<String, Object> uploadFile(MultipartFile imagepath) throws IllegalStateException, IOException {
        String mynewpic = null;
        // 原始图片名称
        String oldFileName = imagepath.getOriginalFilename(); // 获取上传文件的原名
        // 存储路径
        if (imagepath != null && oldFileName != null && oldFileName.length() > 0) {
        //我这写的是绝对路径请注意,springboot 用内置tomcat 展示图片会有问题 稍后在看
            String saveFilePath = "D:\\666";
            File files = new File(saveFilePath);
            if (!files.exists()) {
                files.mkdirs();
            }
            // 新的图片名称
            String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
            // 新图片
            File newFile = new File(saveFilePath + "\\" + newFileName);
            // 将内存中的数据写入磁盘
            imagepath.transferTo(newFile);
            // 将路径名存入全局变量mynewpic
            mynewpic =  newFileName;

            // 将新图片名称返回到前端
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", "成功啦");
            map.put("url", mynewpic);
            return map;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("error", "图片不合法");
            return map;
        }
    }

7、点击添加按钮 输入相关数据,点击"选择"按钮,选择图片,如图点击上传文件

上传图片
显示 图片完成
在这里插入图片描述

8、点击保存存入数据库,js

//执行添加操作
    $('#addBtn1').click(function () {


        // window.parent.document.close();

        var title = $("#title-1").val();
        var content = $("#content-1").val();
        var imagepath = $("#imagepath-1").val();

        $.ajax({
            type: "post",
            datatype: "json",
            url: "/noticeManager/notice/save",
            data: {"title": title, "content": content, "imagepath": imagepath},
            async: true,
            success: function (result) {
                //console.log(result);

                if (result.flag == 'success') {
                    $("#noticeTable").bootstrapTable('refresh');
                    toastr.success("添加成功!");
                } else {
                    toastr.error("添加失败!");
                }
            }
        });
    });

基本内容已经完成了,后续会写一下 在前台显示图片,和编辑图片的操作
各位大哥觉得好的给点个赞
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值