Spring Boot+BootStrap fileInput 多图片上传

一、依赖文件

<link rel="stylesheet" type="text/css" th:href="@{/js/bootstrap/css/bootstrap.css}">
<link rel="stylesheet" type="text/css" th:href="@{/js/bootstrap/fileinput/css/fileinput.css}">
<!-- 加入FileInput -->
<script th:src="@{/js/jquery-3.3.1.min.js}"></script>
<script th:src="@{/js/bootstrap/js/bootstrap.js}"></script>
<script th:src="@{/js/bootstrap/fileinput/js/fileinput.js}"></script>
<script th:src="@{/js/bootstrap/fileinput/js/zh.js}"></script>/*语言环境*/

二、表单

<form class="form" action="#" method="post" enctype="multipart/form-data"  id="pollutionForm">
    <!-- 注意事项:Input type类型为file class为样式 id随意 name随意
         multiple(如果是要多图上传一定要加上,不加的话每次只能选中一张图)-->
    图片:<input type="file" class="file" id="img" multiple name="images"><br>
</form>

三、JavaScript代码

<script>/**/

    var imageData = []; //多图上传返回的图片属性接受数组  这里是因为我在做表单其他属性提交的时候使用,在这里我没有将别的input写出来

    $("#img").fileinput({
        language : ‘zh‘,
        uploadUrl : "/image/save-test",
        showUpload: true, //是否显示上传按钮
        showRemove : true, //显示移除按钮
        showPreview : true, //是否显示预览
        showCaption: false,//是否显示标题
        autoReplace : true,
        minFileCount: 0,
        uploadAsync: true,
        maxFileCount: 10,//最大上传数量
        browseOnZoneClick: true,
        msgFilesTooMany: "选择上传的文件数量 超过允许的最大数值!",
        enctype: ‘multipart/form-data‘,
        // overwriteInitial: false,//不覆盖已上传的图片
        allowedFileExtensions : [ "jpg", "png", "gif" ],
        browseClass : "btn btn-primary", //按钮样式
        previewFileIcon : "<i class=‘glyphicon glyphicon-king‘></i>"
    }).on("fileuploaded", function(e, data) {//文件上传成功的回调函数,还有其他的一些回调函数,比如上传之前...
        var res = data.response;
        console.log(res)
        imageData.push({
            "path": res.data.path,
            "date":res.data.date
        });
        console.log(imageData);
    });
</script>

四、后台代码

//图片类
import java.util.Date;

/**
 * 图片类
 */
public class Img {

    private String name;
    private String path;
    private Date date;

    public Img() {
    }

    public Img(String path, Date date) {
        this.path = path;
        this.date = date;
    }

    public Img(String name, String path, Date date) {
        this.name = name;
        this.path = path;
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "Img{" +
                "name=‘" + name + ‘\‘‘ +
                ", path=‘" + path + ‘\‘‘ +
                ", date=" + date +
                ‘}‘;
    }
}

//图片上传Controller
public class UploadController {

    //fileinput 其实每次只会上传一个文件  多图上传也是分多次请求,每次上传一个文件 所以不需要循环
@RestController
    //@RequestParam("images") 这里的images对应表单中name 然后MultipartFile 参数名就可以任意了
@RequestMapping(value = "/image/save-test",method = RequestMethod.POST)
    public UploadResponseData saveImg(@RequestParam("images") MultipartFile file) throws IOException {
        String pathname = "";
        String returnPath = "";
        if (!file.isEmpty()){
            String fileName = file.getOriginalFilename();
            File path = new File(ResourceUtils.getURL("classpath:").getPath());//获取Spring boot项目的根路径,在开发时获取到的是/target/classes/
            System.out.println(path.getPath());//如果你的图片存储路径在static下,可以参考下面的写法
            File uploadFile = new File(path.getAbsolutePath(), "static/images/upload/");//开发测试模式中 获取到的是/target/classes/static/images/upload/
            if (!uploadFile.exists()){
                uploadFile.mkdirs();
            }
            //获取文件后缀名
            String end = FilenameUtils.getExtension(file.getOriginalFilename());
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            //图片名称 采取时间拼接随机数
            String name = df.format(new Date());
            Random r = new Random();
            for(int i = 0 ;i < 3 ;i++){
                name += r.nextInt(10);
            }
            String diskFileName = name + "." +end; //目标文件的文件名
            pathname = uploadFile.getPath()+ "/" + diskFileName;
            System.out.println(pathname);
            returnPath = "images/upload/" + diskFileName;//这里是我自己做返回的字符串

            file.transferTo(new File(pathname));//文件转存
        }//UploadResponseData 自定义返回数据类型实体{int code, String msg, Object data}
        return new UploadResponseData(CodeEnum.SUCCESS.getCode(),MsgEnum.SUCCESS.getMsg(),new Img(returnPath,new Date()));
    }

}

五、总结吧

最后在这里想说一些问题
    1、spring boot路径获取问题:
     ResourceUtils.getURL("classpath:").getPath(); 在开发环境下获取到的是项目根路径/target/class/

ResourceUtils.getURL("classpath: /static/images/upload/").getPath(); 测试失败

File uploadFile = new File(path.getAbsolutePath(), "static/images/upload/"); 在开发环境下获取到的是/target/class/images/upload/

在将项目打包位war包部署在tomcat之后,/target/class/ --> /WEB-INF/classes/,同理static/images/upload/ --> /WEB-INF/classes/static/images/upload/

2、fileinput需要有返回参数 参数格式随意(不要太随意哈)

3、一下子想不起来了,如果有会继续更

六、如果有错的地方,还请指出,谢谢了!



原文地址:https://www.cnblogs.com/threadj/p/9382525.html

时间: 2024-08-01 14:47:10

Spring Boot+BootStrap fileInput 多图片上传的相关文章

Bootstrap FileInput 多图上传插件 文档属性说明

Bootstrap FileInput 多图上传插件   原文链接:http://blog.csdn.net/misterwho/article/details/72886248?utm_source=itdadao&utm_medium=referral这货融合bootstrap框架,界面相当不错,api非常丰富,可定制内容能满足绝大数的场景. 最近在撸一个项目,用到它,花时间收集了一些文档,整理并翻译了部份内容.备用. github 地址 https://github.com/kartik-

Spring Boot 2.X 实现文件上传(三)

使用 SpringBoot 项目完成单个.多个文件的上传处理,并将上传的文件保存到指定目录下. 代码演示案例 所有的 HTML 页面文件 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>选择上传文件类型</title> </head> <script languag

企业级 Spring Boot 教程 (十七)上传文件

这篇文章主要介绍,如何在springboot工程作为服务器,去接收通过http 上传的multi-file的文件. 构建工程 为例创建一个springmvc工程你需要spring-boot-starter-thymeleaf和 spring-boot-starter-web的起步依赖.为例能够上传文件在服务器,你需要在web.xml中加入标签做相关的配置,但在sringboot 工程中,它已经为你自动做了,所以不需要你做任何的配置. <dependencies> <dependency&

spring mvc 图片上传,图片压缩、跨域解决、 按天生成目录 ,删除,限制为图片代码等相关配置

spring mvc 图片上传,跨域解决 按天生成目录 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ #fs.domains=182=http://172.16.100.182:18080,localhost=http://localhost:8080 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE be

MVC4中基于bootstrap和HTML5的图片上传Jquery自定义控件

场景:mvc4中上传图片,批量上传,上传前浏览,操作.图片进度条. 解决:自定义jquery控件 没有解决:非图片上传时,会有浏览样式的问题; 解决方案; 1.样式 – bootstrap 的css和图标与metro-ui-css的部分css 2.js 自定义控件 3.后台 mvc4 ------------------------------------------------- 1. [class*=border-color] { border: 2px solid; } .border-c

包含修改字体,图片上传等功能的文本输入框-Bootstrap

通过jQuery Bootstrap小插件,框任何一个div转换变成一个富文本编辑框,主要特色: 在Mac和window平台下自动针对常用操作绑定热键 可以拖拽插入图片,支持图片上传(也可以获取移动设备上的照片) 依赖于浏览器标准,没有标准代码:工具条和键盘均可定制,并且能够执行任何浏览器支持的命令 首先看一下效果: 接下来,上代码: 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta c

spring mvc 图片上传,图片压缩、跨域解决、 按天生成文件夹 ,删除,限制为图片代码等相关配置

spring mvc 图片上传,跨域解决 按天生成文件夹 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ #fs.domains=182=http://172.16.100.182:18080,localhost=http://localhost:8080 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE b

Spring MVC多图片上传,多值上传

servlet-context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.spr

SpringMVC+Spring+MyBatis 整合与图片上传简单示例

一.思路: (一) Dao层: 1. SqlMapConfig.xml,空文件即可.需要文件头.2. applicationContext_dao.xml. a) 数据库连接池b) SqlSessionFactory对象,需要spring和mybatis整合包下的.c) 配置mapper文件扫描器. (二)Service层: 1.applicationContext_service.xml包扫描器,扫描@service注解的类.2.applicationContext_trans.xml配置事务