多文件上传(图片,视频,音频,其他文件)
后端部分
文件上传工具类
/**
* 〈文件上传〉
*
* @author 177
* @create 2019-03-12
* @since 1.0.0
*/
public class KitFileUtil {
private static ServletContext servletContext;
public Map<String, Object> kitFileUtil(@RequestParam("uploadFiles") MultipartFile[] uploadFiles, HttpServletRequest request, HttpServletResponse response) {
if (uploadFiles.length==0){
return getError("未选择文件!");
}
// 文件保存目录路径
String savePath = request.getSession().getServletContext().getRealPath("") + "/";
System.out.println("正确路径:" + savePath);
//文件保存目录URL
String saveUrl = request.getContextPath() + "/";
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("video", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
extMap.put("file", "doc,docx,xls,xlsx,ppt,txt,zip,rar,gz,bz2");
extMap.put("audio","mp3,mid,wma,amr,m4a,aif,wav");
//最大文件大小
long maxSize = 11000000;
response.setContentType("text/html; charset=UTF-8");
//判断客户端<form>标记的enctype属性是否是“multipart/form-data"
if (!ServletFileUpload.isMultipartContent(request)) {
return getError("请选择文件。");
}
//检查目录
File uploadDir = new File(savePath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
//return getError("上传目录不存在。");
}
//检查目录写权限
if (!uploadDir.canWrite()) {
return getError("上传目录没有写权限。");
}
//获取请求中dir的参数
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
//校验文件格式(map)中是否存在该键
if (!extMap.containsKey(dirName)) {
return getError("目录名不正确。");
}
//生成文件目录
savePath += dirName + "/";
saveUrl += dirName + "/";
//判断目录是否存在,不存在则创建文件夹
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
//创建年月日目录,
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(System.currentTimeMillis());
savePath += ymd + "/";
saveUrl += ymd + "/";
//判断当天目录是否存在,不存在则创建文件夹
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
String url[] = new String[uploadFiles.length];
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < uploadFiles.length; i++) {
System.out.println(uploadFiles[i]);
// 获取上传文件的名字
String fileName = uploadFiles[i].getOriginalFilename();
// 获取长度
long fileSize = uploadFiles[i].getSize();
// 如果当前上传的文件不为空
if (!uploadFiles[i].isEmpty()) {
// 检查文件大小
if (uploadFiles[i].getSize() > maxSize) {
return getError("上传文件大小超过限制。");
}
// 截取扩展名 toLowerCase用于将大写字符转换为小写 +1表示不包括.开始截取
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 校验该扩展名是否在该键对应的格式中 contains:当且仅当此字符串包含指定的char值序列时,返回true
if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
//文件重命名:时分秒+随机数+.+后缀格式 Random().nextInt(1000)生成一个0~999的随机整数
String newFileName = df.format(System.currentTimeMillis()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try {
// 保存文件
System.out.println(saveUrl + newFileName);
// 复制 source 文件到 target
FileCopyUtils.copy(uploadFiles[i].getInputStream(), new FileOutputStream(savePath + newFileName));
} catch (Exception e) {
return getError("上传文件失败。");
}
url[i] = saveUrl + newFileName;
// map.put("error", 0);
// map.put("url", saveUrl + newFileName);
// return map;
}
}
map.put("error", 0);
map.put("url", url);
return map;
// return getError("服务器端错误。");
}
private Map<String, Object> getError(String message) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("error", 101);
map.put("message", message);
return map;
}
}
文件上传Controller
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public Object uploadVideo(@RequestParam("uploadFiles") MultipartFile[] uploadFiles,
HttpServletRequest request,
HttpServletResponse response) {
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Object> map2 = new HashMap<String, Object>();
KitFileUtil kitFileUtil = new KitFileUtil();
map = kitFileUtil.kitFileUtil(uploadFiles, request, response);
String error = map.get("error").toString();
if ("101".equals(error)) {
map2.put("error", 101);
map2.put("message", map.get("message"));
return map;
}
map2.put("error", 0);
String url[] = (String[]) map.get("url");
map2.put("url", url);
return JSONObject.toJSON(map2);
}
配置文件需要
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!-- 指定所上传文件的总大小,单位字节。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="20480000" />
</bean>
前端部分
HTML(测试用)
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="./js/common/jquery/jQuery-2.2.0.min.js"></script>
</head>
<body>
<div class="picture-box" style="text-align:center;height: 150px;">
<input class="chooseImage" name="image" type="file" onchange="previewFiles('image')" accept="image/*" multiple>
<input id="" type="button" onclick="uploadFile('image')" value="提交">
<div id="preview"></div>
</div>
<div class="video-box" style="text-align:center;height: 350px;">
<input class="chooseVideo" name="video" type="file" onchange="uploadFiles(this)" accept="video/*" multiple value=""><br>
<div>
<video id="videoView" width="420" autoplay="autoplay" controls="controls" src="" loop="-1">
您的浏览器不支持 HTML5 video 标签
</video>
</div>
</div>
<div class="audio-box" style="text-align:center">
<input class="chooseAudio" name="audio" type="file" onchange="uploadFiles(this)" accept="audio/*" multiple value="">
<div style="text-align:center">
<audio id="audioView" controls="controls" height="100" src="" width="100">
您的浏览器不支持 HTML5 audio 标签
</audio>
</div>
</div>
</body>
ajax提交
<!-- 图片上传 -->
<script>
function previewFiles() {
if (typeof FileReader == undefined) {
alert("浏览器不支持FileReader");
}
var preview = document.querySelector('#preview');
var files = document.querySelector('input[class=chooseImage]').files;
$(document).find("#preview").empty();
function readAndPreview(file) {
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
}
function uploadFile(dir) {
var files = document.querySelector('input[class=chooseImage]').files;
var formData = new FormData();
var uploadFiles = [];
for (var i = 0; i < files.length; i++) {
uploadFiles.push(files[i]);
}
uploadFiles.forEach(function (file, index) {
formData.append('uploadFiles', file); //添加图片信息的参数
});
formData.append('dir', dir); //添加其他参数
$.ajax({
url: '/survey/v2/uploadFile/uploadFile',
type: 'POST',
cache: false, //上传文件不需要缓存
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (data) {
var rs = eval(data);
if (rs.url.length > 0) {
alert('上传成功!');
} else {
alert(rs.msg);
}
},
error: function (data) {
alert("上传失败");
}
})
}
</script>
<!-- 文件上传 -->
<script>
function uploadFiles(obj) {
var chooseFile = $(obj).prop("class");
var dir = $(obj).prop("name")
var files = document.querySelector("input[class='" + chooseFile + "']").files;
var formData = new FormData();
var uploadFiles = [];
for (var i = 0; i < files.length; i++) {
uploadFiles.push(files[i]);
}
uploadFiles.forEach(function (file, index) {
formData.append('uploadFiles', file); //添加图片信息的参数
});
formData.append('dir', dir); //添加其他参数
$.ajax({
url: '/survey/v2/uploadFile/uploadFile',
type: 'POST',
cache: false, //上传文件不需要缓存
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (data) {
var rs = eval(data);
if (rs.error == 0) {
alert('上传成功!');
//图片回显
if (dir == "image") {
$("#imageView").attr("src", rs.url);
}
//视频回显
if (dir == "video") {
$("#videoView").attr("src", rs.url);
}
//音频回显
if (dir == "audio") {
$("#audioView").attr("src", rs.url);
}
} else {
alert(rs.message);
}
},
error: function (data) {
alert("上传失败");
}
})
}
</script>