简单介绍:需求上让实现,图片上传,并且可以一次上传9张图,图片格式还有要求,网上找了一个测试了下,好用,不过也得改,仅仅是实现了功能,其他不尽合理的地方,还需自己打磨。

代码:

//html
<div class="col-md-12">
<label class="control-label flex" style="margin-top: 10px;">
上传附件<span class="star align-items">*</span>
</label>
  <form id="imgForm">
<div class="">
<img th:src="@{/assets-new/apps/img/shangchuan.png}" id="imgIcon"
width="35px" height="35px"/>
<input type="file" id="seledIcon" style="display:none"
multiple="multiple" accept="image/gif,image/jpg,image/png,image/JPEG"/>
</div>
  </form>
<input type="hidden" name="contractIcon" id="contractIcon"/>
</div>
<div id="imgBox"></div>
<button id="btn">上传</button> 
//这里的form 是专门用来做上传用的(言外之意是还有别的form)。专门 专门 专门 因为新增或者编辑的时候我们上传图片,最后肯定要保存的,点击保存,触发表单form提交,就会冲突
//说明一下,accept可以直接设置"image/*"是所有类型的图片格式 输入accept= idea会给出提示的,可以自己看看
//js代码 
$("#imgIcon").on("click", function () {
$("#seledIcon").trigger("click");
});
//这段代码建议放到初始化里边 另外 url要加上 根路径 rootPath,否则上传不了不怪我哦
<script type="text/javascript" th:inline="javascript" xmlns:th="http://www.w3.org/1999/xhtml">
<![CDATA[
imgUpload({
inputId:'seledIcon', //input框id
imgBox:'imgBox', //图片容器id
buttonId:'btn', //提交按钮id
upUrl: rootPath +'/oper/contract/uploadImg', //提交地址
data:'file', //参数名
num:"9"//最多上传图片个数,可以设置很多,看你服务器大小以及性能了
});
]]>
</script> 
//js代码
var imgSrc = []; //存放图片路径
var imgFile = []; //存放文件流
var imgName = []; //存放图片名字
//选择图片的操作
function imgUpload(obj) {
debugger;
var oInput = '#' + obj.inputId;
var imgBox = '#' + obj.imgBox;
var btn = '#' + obj.buttonId;
//用on是因为它可以动态的绑定事件
$(oInput).on("change", function() {
     imgFile = [];//保证二次点击上传的时候第一次的file不会被再次上传
//获取type=file的input
var fileImg = $(oInput)[0];
//得到所有的图片列表
var fileList = fileImg.files;
for(var i = 0; i < fileList.length; i++) {
      if(fileList[i].size<1021*1024){
//得到每个图片的路径
var imgSrcI = getObjectURL(fileList[i]);
//向文件名的数组末尾添加此文件名
imgName.push(fileList[i].name);
//向路径的数组末尾添加路径
imgSrc.push(imgSrcI);
//在文件流数组的末尾添加文件
imgFile.push(fileList[i]);
 }
     }
//将图片展示出去
addNewContent(imgBox);
}); $(btn).on('click', function() {
if(!limitNum(obj.num)){
layer.msg("最多只能上传"+obj.num+"张照片!");
return false;
} //用FormData对象上传
var fd = new FormData($('#imgForm')[0]);
//由于fd对象中已经包含<input type='file'>的input标签,如果不删除,就会造成重复上传
fd.delete("file");
//将文件流循环添加到FormData对象中
for(var i=0;i<imgFile.length;i++){
fd.append(obj.data,imgFile[i]);
}
//上传所有的图片
submitPicture(obj.upUrl, fd);
})
}
//图片展示
function addNewContent(obj) {
$(imgBox).html("");
for(var a = 0; a < imgSrc.length; a++) {
var oldBox = $(obj).html();
$(obj).html(oldBox + '<div class="imgContainer"><img title=' + imgName[a] + ' alt=' + imgName[a] + ' src=' + imgSrc[a] + ' onclick="imgDisplay(this)"><p onclick="removeImg(this,' + a + ')" class="imgDelete">删除</p></div>');
}
}
//删除
function removeImg(obj, index) {
//向数组中删除元素
imgSrc.splice(index, 1);
imgFile.splice(index, 1);
imgName.splice(index, 1);
var boxId = "#" + $(obj).parent('.imgContainer').parent().attr("id");
addNewContent(boxId);
}
//限制图片个数
function limitNum(num){
if(!num){
return true;
}else if(imgFile.length>num){
return false;
}else{
return true;
}
} //上传(将文件流数组传到后台)
function submitPicture(url,data) {
debugger;
for (var p of data) {
console.log(p);
}
if(url&&data){
$.ajax({
url: url,
type: "post",
data: data,
async: true,
//下面这两个要写成false,要不然上传不了。
processData: false,
contentType: false,
success: function(dat) {
debugger;
layer.msg("上传成功");
},
error:function(xhr,emsg,e) {
//打印ajax发生的错误
console.log(e);
//答应出ajax请求返回的文本信息
console.log(xhr.responseText());
}
});
}else{
layer.msg('数据格式不正确!');
}
}
//当鼠标移到图片上时,显示x删除
function imgDisplay(obj) {
var src = $(obj).attr("src");
var imgHtml = '<div style="width: 100%;height: 100vh;overflow: auto;background: rgba(0,0,0,0.5);text-align: center;position: fixed;top: 0;left: 0;z-index: 1000;"><img src=' + src + ' style="margin-top: 100px;width: 70%;margin-bottom: 100px;"/><p style="font-size: 50px;position: fixed;top: 30px;right: 30px;color: white;cursor: pointer;" onclick="closePicture(this)">×</p></div>'
$('body').append(imgHtml);
}
//关闭
function closePicture(obj) {
$(obj).parent("div").remove();
}
//图片预览路径
function getObjectURL(file) {
var url = null;
if(window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if(window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if(window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;

//后台java代码
//获取配置里的路径 写在Controller里
@Value("${constant.image_path}")
private String imagePath; @Value("${constant.image_temp_path}")
private String imageTempPath; @RequestMapping("/uploadImg")
@ResponseBody
public String uploadImg(MultipartFile file[]) throws Exception {
List<String> list = new ArrayList<>();
for (MultipartFile f : file) {
// 图片的名字用毫秒数+图片原来的名字拼接
String imgName = System.currentTimeMillis() + f.getOriginalFilename();
//上传文件
uploadFileUtil(f.getBytes(), imageTempPath, imgName);
list.add(imgName);
}
String str = StringUtils.join(list,",");
return str;
} private void uploadFileUtil(byte[] file, String imgPath, String imgName) throws Exception {
File targetFile = new File(imgPath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(imgPath + File.separator + imgName);
out.write(file);
out.flush();
out.close();

主要的改动是在uploadFileUtil方法中,原博文的上传图片,上传后的图片名字前面还多了一个上级文件夹的名字,经过我修改后的就没有了,

另外 springboot内置tomact的的文件传输默认为1MB,所以我在js里边添加了一个if条件限定文件大小小于1M也就是1024*1024

随笔到这里就完了,下边是一些注意事项和小问题。

————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

首先一个很重要的内容,因为这里使用的是表单提交请求,所以存在一个问题,如果我们在做新增或者编辑的时候,最后肯定是要提交form表单来把数据传递到后台的,因为有id是imgForm图片提交的form存在,所以写在imgForm之外,addForm之内的一些表单信息后台就获取不到,也就是下边的 备注notes 和 别名alias 就不能够被addForm传递到后台,后台是null,要解决这个问题,只要把notes 和 alias这两个表单放到 imgForm上边就OK。

//html  
<form action="" class="horizontal-form" method="post" id="addForm" autocomplete="off">
<div class="col-md-6">
<label class="control-label flex" style="margin-top: 10px;" >
编号<span class="star align-items">*</span>
</label>
<input type="text" id="number" name="number"
class="form-control" maxlength="50" placeholder="编号"/>
</div>
<div class="col-md-6">
<label class="control-label flex" style="margin-top: 10px;">
类型<span class="star align-items">*</span>
</label>
<select id="s_type" name="s_ype" class="form-control js-example-basic-single">
<option th:each="status : ${typeList}" th:value="${status.dictCode}"
th:text="${status.dictName}"
xmlns:th="http://www.w3.org/1999/xhtml"></option>
</select>
</div>
<div class="col-md-6">
<label class="control-label flex" style="margin-top: 10px;">
生效时间<span class="star align-items">*</span>
</label>
<div class="input-group-control date-picker">
<input class="form-control" type="text" name="startTime" id="startTime" maxlength="50" placeholder="请输入生效时间"/>
</div>
</div>
<div class="col-md-6">
<label class="control-label flex" style="margin-top: 10px;">
失效时间<span class="star align-items">*</span>
</label>
<div class="input-group-control date-picker">
<input class="form-control" type="text" name="endTime" id="endTime" maxlength="50" placeholder="请输入失效时间"/>
</div>
</div>
<br /><br /> <div class="col-md-12">
<label class="control-label flex" style="margin-top: 10px;">
上传附件<span class="star align-items">*</span>
</label>
<form id="imgForm">
<div class="" id="imgDiv">
<img th:src="@{/assets-new/apps/img/shangchuan.png}" id="imgIcon"
width="35px" height="35px"/>
<input type="file" id="seledIcon" style="display:none"
multiple="multiple" accept="image/gif,image/jpg,image/png,image/JPEG"/>
</div></form>
<input type="hidden" name="contractIcon" id="contractIcon"/>
</div>
  <div class="col-md-12">
<label class="control-label flex" style="margin-top: 10px;">
备注
</label>
</div>
<div class="col-md-12">
<textarea id="notes" name="notes" class="form-control" placeholder="请填写备注信息" maxlength="200"></textarea>
</div>
  <div class="col-md-12">
    <input type="text" id="alias" name="alias" class="form-control" placeholder="别名"/>
  </div>
<br />
<br />
</form> 

在说一点:springboot 内置tomact的的文件传输默认为1MB,超过这个会报错哦,要注意,限制大小;要么就是修改文件传输的大小限制,这个我没改,因为老大不让动配置,emmm,不过呢,给你们个链接,我觉得这个应该会好使https://blog.csdn.net/duangecho/article/details/80383720

还有的就是一些,很细节方面的问题了,比如说,原文的imgbox真的不太美观,我改了,文章没体现,下一篇(五)会说的,还有就是删除样式也不太好看=3=!\(^o^)/

总结:好用是好用,但是对于图片大小样式什么的没有具体的限定,另外展示图片仅仅是吧图片放在了html中,体验感不太好,嗯,反正得改。。。。有一点,原来的博主js写的挺全面的,什么 删除啦,点击放大预览啦都有的,值得借鉴,当然也得修改修改

原文链接:https://blog.csdn.net/jtshongke/article/details/78516559

SpringBoot图片上传(四) 一个input上传N张图,支持各种类型的更多相关文章

  1. python 开发一款图片压缩工具(四):上传图床

    上一篇使用了 pngquant 图片压缩工具进行压缩,并通过 click 命令行工具构建了 picom 包.这篇的主要功能是实现图片上传. 图片上传功能的实现 通过 pngquant 压缩图片后,得到 ...

  2. 点击一个div ,把div里的某个参数的值,传到一个input里面

    ​​​

  3. netty系列之:一个价值上亿的网站速度优化方案

    目录 简介 本文的目标 支持多个图片服务 http2处理器 处理页面和图像 价值上亿的速度优化方案 总结 简介 其实软件界最赚钱的不是写代码的,写代码的只能叫马龙,高级点的叫做程序员,都是苦力活.那么 ...

  4. 用Canvas+Javascript FileAPI 实现一个跨平台的图片剪切、滤镜处理、上传下载工具

    直接上代码,其中上传功能需要自己配置允许跨域的文件服务器地址~ 或者将html文件贴到您的站点下同源上传也OK. 支持: 不同尺寸图片获取. 原图缩小放大. 原图移动. 选择框大小改变. 下载选中的区 ...

  5. SpringBoot图片上传(五) 上一篇的新版本,样式修改后的

    简单描述:一次上传N张图片(N可自定义):上传完后图片回显,鼠标放到已经上传的图片上后,显示删除,点击后可以删除图片,鼠标离开后,图片恢复. 效果:一次上传多个图片后的效果 上传成功: 鼠标悬浮到图片 ...

  6. SpringBoot图片上传(三)——调用文件上传项目的方法(同时启动两个项目)

    简单说明:图片上传有一个专门的工程A,提供了图片的上传和下载预览,工程B涉及到图片上传以及回显,都是调用的工程A的方法,言外之意就是要同时启动两个项目. 代码: //工程B的html代码 <di ...

  7. HTML5 原生API input file 来实现多图上传,并大图预览

    闲来无事,突然想用原生来实现图片的多图上传. 一.效果图大致如下: 1.上传时可以选择多图 2.上传之后缩略图下过图如下: 3.点击缩略图,大图展示当前所点击的图片,并可以左右滑动查看其它的缩略图对应 ...

  8. 基于Metronic的Bootstrap开发框架经验总结(5)--Bootstrap文件上传插件File Input的使用

    Bootstrap文件上传插件File Input是一个不错的文件上传控件,但是搜索使用到的案例不多,使用的时候,也是一步一个脚印一样摸着石头过河,这个控件在界面呈现上,叫我之前使用过的Uploadi ...

  9. Bootstrap文件上传插件File Input的使用

    基于Metronic的Bootstrap开发框架经验总结(5)--Bootstrap文件上传插件File Input的使用 Bootstrap文件上传插件File Input是一个不错的文件上传控件, ...

随机推荐

  1. PHP之pear包总结

    现在我们开发的时候,尤其是使用框架进行项目开发的时候,都会有一个专门的包管理工具,对,那就是composer,使用这个工具可以简单快速的引入一个代码包,十分快捷好用.接下就总结一下,经常使用到的pea ...

  2. java 反射的基本操作

    一.反射的概述JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法和属性:这种动态获取的信息以及动态调用对象的方法的功能称为j ...

  3. [转帖]SAP BASIS日常需要做的工作

    SAP BASIS日常需要做的工作 https://www.cnblogs.com/swordxia/p/4790684.html SAP Basis的一些日常工作包括用户权限管理.集团管理.数据库管 ...

  4. Linux 系统巡检常用命令

    Linux系统巡检常用命令   # uname -a # 查看内核/操作系统# cat /etc/centos-release # 查看centos操作系统版本# cat /proc/cpuinfo ...

  5. Redis的发布与订阅

    业务: 运用数据与信息指导小药工的采购生产与销售行为 需求背景: (1)药工汇小程序用户(即小型中药初加工用户)需要知道自己加工的品种的价格涨跌信息和品种相关资讯) 需求分析拆解: (1)使用爬虫程序 ...

  6. Amazon SNS (Simple Notification Service) Using C# and Visual Studio

    SNS (Amazon Simple Notification Services) Amazon SNS (Amazon Simple Notification Services) is a noti ...

  7. rest framework 解析器,渲染器

    解析器 解析器的作用 解析器的作用就是服务端接收客户端传过来的数据,把数据解析成自己可以处理的数据.本质就是对请求体中的数据进行解析. 请求体相关字段: Accept:指定了接收的数据类型 Conte ...

  8. [M$]重装或更换主板后提示“由于指定产品密钥激活次数“ office 2016

    https://answers.microsoft.com/zh-hans/msoffice/forum/all/%E6%8C%87%E5%AE%9A%E4%BA%A7%E5%93%81%E5%AF% ...

  9. python的内置模块xml模块方法 xml解析 详解以及使用

    一.XML介绍 xml是实现不同语言或程序直接进行数据交换的协议,跟json差不多,单json使用起来更简单,不过现在还有很多传统公司的接口主要还是xml xml跟html都属于是标签语言 我们主要学 ...

  10. java matlab 混合编程 Failed to find the required library mclmcrrt9_2.dll on java.library.path.

    问题描述: Exception in thread "main" java.lang.UnsatisfiedLinkError: Failed to find the requir ...