以下功能亲测,部分样式和js根据情况自行调整
<%--
Created by IntelliJ IDEA.
User: yutyi
Date: 2018/9/3
Time: 22:44
To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>${title}title>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<%@include file="/common/meta.jsp"%>
head>
<body class="hold-transition skin-blue">
<div>
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box" style="margin-bottom: 80px;">
<form id="myform" class="form-horizontal" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="col-xs-2 control-label">附件label>
<div class="col-xs-10">
<label style="border: 1px dashed #dbdadd;padding: 10px;background-color: #80808033;">
<input style="position:absolute;opacity: 0;width: 35px;height: 35px;left: 5px;" id="choose-file" multiple type="file" name="file" accept="image/gif,image/jpeg,image/x-png,image/png"/>
<div style="width: 35px;height: 35px;background: url('${contextPath}/static/img/upload/icon_upload.png');background-size: 35px 35px;">div>
label>
<div class="file-list" style="display: inline-block;width: auto;position: relative;top: -30px;">
div>
div>
div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<img id="imgSrc" src="" alt="" style="width: 570px;height: 570px;"/>
div>
div>
div>
div>
div>
<div class="dialog-footer">
<button type="button" class="btn btn-primary" onclick="doSave();">保存button>
<button type="button" class="btn btn-default" onclick="doClose();">关闭button>
div>
form>
div>
div>
div>
section>
div>
<script type="text/javascript">
/*
* 保存
*/
function doSave(){
var valid = $('#myform').valid();
if (valid) {
//使用formData发送ajax请求,注意[0],发现很多博客都没有写
var formData = new FormData($("#myform")[0]);
//删除formData中的File对象,设置将我们需要上传的fileList中File对象
formData.delete("file");
for (var i=0;i<fileList.length;i++) {
formData.append("file",fileList[i]);
}
//添加需要删除的已上传的图片的id,后台解析删除
formData.append("removeList",removeList);
$.ajax({
url : "${contextPath}/upload/multi",
data : formData,
type : "post",
dataType : "json",
cache : false,//上传文件无需缓存
processData : false,//用于对data参数进行序列化处理 这里必须false
contentType : false, //必须
success : function (resp) {
if(resp.success){
alert("保存成功");
}else{
alert("保存失败");
}
}
});
}
}
$(function () {
/**
* 编辑页面,获取已上传的图片,根据自己的需求更改
* */
var deviceId = "${param.deviceId}";
if (deviceId) {
var url = "${contextPath}/device/img";
$.post(url,{deviceId:deviceId},function (data) {
for (var i=0;i<data.length;i++) {
//attachmentId是已上传图片的id,一般图片存储在服务器端规定的某个文件夹,可以使用nginx代理来回显
$list.append('data[i].attachmentId+'">+data[i].url+' alt="" style="width: 55px;height: 55px;" onclick="showImage(this)"/>×')
}
});
}
});
/*
* 图片上传
* */
//选择文件按钮
$file = $("#choose-file");
//回显的列表
$list = $('.file-list');
//选择要上传的所有文件
fileList = [];
//已添加需要删除的文件
removeList = "";
//当前选择上传的文件
var curFile;
// 选择按钮change事件,实例化fileReader,调它的readAsDataURL并把原生File对象传给它,监听它的onload事件,load完读取的结果就在它的result属性里了。它是一个base64格式的,可直接赋值给一个img的src
$file.on('change',function(){
//原生的文件对象(File对象数组),相当于$file.get(0).files[0];
curFile = this.files;
//将curFile数组和FileList数组合并
fileList = fileList.concat(Array.from(curFile));
console.log(fileList);
for(var i=0,len = curFile.length;i < len;i++){
reviewFile(curFile[i])
}
});
//回显图片
function reviewFile(file){
//实例化fileReader,
var fd = new FileReader();
//获取当前选择文件的类型
var fileType = file.type;
//调它的readAsDataURL并把原生File对象传给它,
fd.readAsDataURL(file);//base64
//监听它的onload事件,load完读取的结果就在它的result属性里了
fd.onload = function(){
$list.append('this.result+'" alt="" style="width: 55px;height: 55px;" onclick="showImage(this)"/>×')
}
}
//删除图片
$(".file-list").on('click','.file-del',function(){
var $parent = $(this).parent();
var index = $parent.index(".file-item");
//index==-1时表示是已上传回显的图片
if (index == -1) {
removeList += $parent.attr("data-id")+",";
}
console.log(removeList);
//删除选择的图片
fileList.splice(index,1);
$parent.remove();
});
//点击图片显示放大图(使用bootstrap的模态框)
function showImage(e) {
$("#imgSrc").attr("src",e.src);
$('#myModal').modal('show');
}
script>
body>
html>
上传多图片的后端控制类,仅供参考
package zyun.bme.platform.device.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import zyun.bme.platform.common.ConfigProperties;
import zyun.bme.platform.common.Constants;
import zyun.bme.platform.common.U;
import zyun.bme.platform.device.entity.Attachment;
import zyun.bme.platform.device.service.AttachmentService;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* 多文件上传控制器
*
* @author yutyi
* @date 2018/09/27
*/
@Controller
@RequestMapping("/upload")
public class MultiFileUploadController {
private Logger logger = LoggerFactory.getLogger(MultiFileUploadController.class);
@Autowired
private AttachmentService attachmentService;
/**
* 文件上传(支持多个文件),单个文件时也可以使用MultipartFile作为方法参数
* @param request
* @return
* @throws IOException
*/
@RequestMapping(value = {"/multi"})
public String multiFileUpload(MultipartHttpServletRequest request,@RequestParam(required = false)String removeList) throws IOException {
//删除需要删除的图片,仅通过图片id删除表中数据
if (StringUtils.isNotEmpty(removeList)) {
String[] images = removeList.split(",");
ArrayList<Long> list = new ArrayList<>();
for (String image : images) {
if (StringUtils.isNotEmpty(image)) {
list.add(Long.parseLong(image));
}
}
if (list.size() > 0) {
attachmentService.deleteImage(list);
}
}
//获取所有的文件上传表单内容
List<MultipartFile> files = request.getFiles("file");
if (files == null || files.size() == 0 ) {
return "forward:/device/save";
}
for (MultipartFile file : files) {
//获取原始文件名
String filename = file.getOriginalFilename();
//获取文件大小
int size = (int) file.getSize();
//保存路径
String tempPath = ConfigProperties.getProp(Constants.UPLOAD_LOCATION);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(System.currentTimeMillis());
String format = simpleDateFormat.format(date);
String[] split = format.split("-");
//添加年月日目录
tempPath = tempPath+"/"+split[0]+"/"+split[1]+"/"+split[2];
File fileDir = new File(tempPath);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
//保存图片信息的实体类,根据自己情况编写
Attachment attachment = new Attachment();
attachment.setAttachmentId(U.id());
attachment.setDataId(dataId);
attachment.setName(filename);
String url = tempPath+"/"+System.currentTimeMillis()+filename.substring(filename.indexOf("."));
attachment.setUrl("/file/download"+url.substring(tempPath.indexOf("upload/")+6));
attachment.setFileSize(size);
attachmentService.insert(attachment);
//上传文件
BufferedOutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(new File(url)));
//上传文件
out.write(file.getBytes());
out.flush();
logger.debug("上传文件的原始文件名:" + filename);
logger.debug("上传文件的路径:"+url);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
return "forward:/device/save";
}
}