1.首先引入样式:
.img-cont{
width:100%;
height:100%;
border:1px solid #eeeeee;
margin:0px auto;
}
.img-cont>div{
width:300px;
height:260px;
border:1px solid #777;
float:left;
margin:20px 0 0 20px;
}
.img-cont>div>div{
width:300px;
height:220px;
border:1px solid #ffffff;
}
.img-cont>div>a{
width:60px;
height:30px;
border-radius:4px;
line-height: 30px;
text-align: center;
color:#fff;
display: block;
background: #317ef3;
margin:5px 0 0 0px;
cursor: pointer;
}
.hide{
display: none !important;
}
2.然后在页面中添加:
<meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />
非表单提交,必须添加此参数
3.HTML:
<form enctype="multipart/form-data">
<input type="file" id="file" onchange='PreviewImage(this)' />
<select id="imgName" class="scm-form-item" name="imgName">
<option value="">请选择证件类型</option>
<option value="营业执照">营业执照</option>
<option value="餐饮服务许可证">餐饮服务许可证</option>
<option value="开户许可证">开户许可证</option>
<option value="开票信息">开票信息</option>
<option value="法人身份证复印件">法人身份证复印件</option>
<option value="采购经办人身份证复印件">采购经办人身份证复印件</option>
</select>
<button type="button" class="scm-btn-oper" id="uploadImgs" onclick="uploadCreditImgs();"><i class="mileegou" style="font-size:12px;color:#fff;"></i>上传图片</button>
</form>
<!-- 图片展示容器 -->
<div class="img-cont"></div>
4.JS部分
/**图片上传*/
var id=0;
var ims = [];//用来存放图片文件
var imsName = [];//用来存放对应的文件名称(选择框所选)
function PreviewImage(imgFile) {
//这里校验为实际项目需求,不需要可删除
if($("#imgName").val() == null || $("#imgName").val() == ""){
layer.alert("请选择证件类型再进行上传!",{"title":"提示"});
//重置表单
resetForm(imgFile);
return;
}
//校验图片类型
var pattern = /(\.*.jpg$)|(\.*.png$)|(\.*.jpeg$)|(\.*.gif$)|(\.*.bmp$)/;
if(!pattern.test(imgFile.value)) {
layer.alert("系统仅支持jpg/jpeg/png/gif/bmp格式的照片!",{"title":"提示"});
imgFile.focus();
}else{
//对上传图片最多数量进行限制
if($(".img-cont").children().length > 5){
layer.alert("最多上传6张图片!",{"title":"提示"});
return;
}
//定义图片路径
var path;
//添加显示图片的HTML元素
id += 1;
$(".img-cont").append("<div><div id='"+id+"'><img src='' /></div><a class='hide delete-btn' name='"+id+"'>删除</a></div>");
//判断浏览器类型
if(document.all){
//兼容IE
imgFile.select();
path = document.selection.createRange().text;
document.getElementById(id).innerHTML="";
document.getElementById(id).style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src=\"" + path + "\")";//使用滤镜效果
}else{
//兼容其他浏览器
path = URL.createObjectURL(imgFile.files[0]);
document.getElementById(id).innerHTML = "<img src='"+path+"' width='300' height='220' />";
}
// console.log(imgFile.files[0].name)
//将图片文件放入数组中
ims.push(imgFile.files[0]);
imsName.push($("#imgName").val());
//重置表单
resetForm(imgFile);
}
}
/**重置表单,允许用户连续添加相同的图片*/
function resetForm(imgFile){
$(imgFile).parent()[0].reset();
}
/**控制"按钮"显示与隐藏*/
$(".img-cont").off("mouseenter","div").on("mouseenter","div",function(){
var that=this;
var dom=$(that).children("a");
dom.removeClass("hide");
//为点击事件解绑,防止重复执行
dom.off("click");
dom.on("click",function(){
//删除当前图片
dom.parent().remove();
//从数组中相应删除对应的图片文件及名称
ims.splice(dom.attr("name") - 1,1);
imsName.splice(dom.attr("name") - 1,1);
});
}).off("mouseleave","div").on("mouseleave","div",function(){
var that=this;
$(that).children("a").addClass("hide");
})
/**
* ajax图片上传
*/
var imageMapperUrl;
function uploadCreditImgs(){
var formData = new FormData();
if(ims == null || ims.length == 0){
layer.alert("暂无可上传的图片!",{"title":"提示"});
return;
}else{
for(var i = 0; i < ims.length; i++){
//使用FormData循环添加图片文件,这里注意 "file" 名称对应后台获取图片参数名称
formData.append("file", ims[i]);
}
}
$.ajax({
async: false,
type: 'POST',
data: formData,
url:'${ctx}/applyCredit/uploadCreditPic.do',
cache : false,
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须*/
dataType: 'json',
success: function (data) {
if(data.optFlag=='yes'){
layer.alert(data.optDesc,{"title":"提示"});
$("#file").hide();
imageMapperUrl = data.res;
}else{
layer.alert(data.optDesc,{"title":"提示"});
}
return;
}
});
}
5.JAVA后台代码:
/**
* 上传营业执照等照片
* @param imgfiles
* @return
*
* @author Tom
*/
@ResponseBody
@RequestMapping(value = "uploadCreditPic.do", method = RequestMethod.POST)
public Map<String,Object> uploadCreditPic(@RequestParam(value = "file") MultipartFile[] imgfiles) {
Map<String,Object> res = new HashMap<>();
try{
List<String> urls = CommonUtil.fileToLocal(imgfiles, "recImage", DateUtil.date2String(4, new Date()));
// 保存上传图片的路径
if (urls != null && urls.size() > 0) {
String url = "";
for(String s : urls){
if(url == null || url == ""){
url = s;
}else{
url = url + "," + s;
}
}
res.put("optFlag", "yes");
res.put("optDesc", "图片上传成功!");
res.put("res",url);
}else{
res.put("optFlag", "yes");
res.put("optDesc", "暂无图片上传!");
}
} catch (Exception e) {
res.put("optFlag", "no");
res.put("optDesc", "上传图片失败!");
log.error("*************图片上传失败", e);
}
return res;
}
这里的fileToLocal方法是公司其他同事已经编写,个人觉得不太好,可以用自己的方法代替上传,还是写出具体方法的实现,如下:
public static List<String> fileToLocal(MultipartFile[] fileArray, String busiType, String subClass) throws Exception {
List<String> rpathList = new ArrayList(0);
if (fileArray != null && fileArray.length > 0) {
for(int i = 0; i < fileArray.length; ++i) {
MultipartFile file = fileArray[i];
if (file != null && !file.isEmpty()) {
String fname_ = fileToLocal(file, busiType, subClass, i);
rpathList.add(fname_);
}
}
}
return rpathList;
}
public static String fileToLocal(MultipartFile imgFile, String busiType, String subClass, int index) throws Exception {
String FileSep = "/";
//配置文件中配置的文件存储路径
String baseDiskPath = Constants.SYS_FILE_BASE_PATH;
String relaImgDir = FileSep + "imgs" + FileSep + busiType;
if (subClass != null && !"".equals(subClass)) {
relaImgDir = relaImgDir + FileSep + subClass;
}
File fileDir = new File(baseDiskPath, relaImgDir);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
String fileName = imgFile.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
String tempImageName = SequenceUtil.getImgSequence() + index + suffix;
File target = new File(fileDir, tempImageName);
imgFile.transferTo(target);
String relateImgName = FileSep + "upload" + relaImgDir + FileSep + tempImageName;
return relateImgName;
}
public static String getImgSequence() {
++intIndex;
if (intIndex > 99) {
intIndex = 0;
}
return sdFormatSS4.format(new Date()) + intIndex;
}