最近有个功能需要实现批量上传图片,然后实现图片预览,因为项目比较老,同时对界面和用户操作体验也要求不太高,就没去找网上的开源插件,直接写了个简单的功能,这里做个记录备份
因为这个是实验性的小代码,就没做太多的验证和界面调整
image.png可以实现乱序删除
image.png这就是简单的功能界面,下面就是代码
首先是SpringMVC的xm需要配置下
<!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver 说明: p:defaultEncoding="UTF-8":这里设置默认的文件编码为UTF-8,必须与用户JSP的默认编码一致;
p:maxUploadSize="5000000":指定文件上传大小,单位为字节; p:uploadTempDir="fileUpload/temp":文件上传临时目录,上传完成后,就会将临时文件删除; -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" p:maxUploadSize="5000000" p:uploadTempDir="fileUpload/temp">
</bean>
JSP+js
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
response.setHeader("Cache-Control","no-store");//HTTP 1.1
response.setHeader("Pragma","no-cache");//HTTP 1.0
response.setDateHeader("Expires",0);//prevents caching at the proxy server
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'batchFileUpload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="<%=basePath%>static/css/webuploader.css"/>
<script type="text/javascript" src="<%=basePath%>static/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="<%=basePath%>static/js/ajaxfileupload.js"></script>
<script type="text/javascript" src="<%=basePath%>static/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=basePath%>static/js/jquery.json-2.4.js" charset="UTF-8"></script>
<script type="text/javascript" src="<%=basePath%>static/js/jquery.validate.js"></script>
<script type="text/javascript" src="<%=basePath%>static/js/jquery.Jcrop.js"></script>
<script type="text/javascript" src="<%=basePath%>static/js/webuploader.nolog.js"></script>
<script type="text/javascript">
$(function(){
//动态打开file标签
$("#changeImg").click(function(){
var files = document.getElementsByName("file");
for(var i = 0;i<files.length;i++)
{
if($(files[i]).val()=='')
{
$(files[i]).click();
break;
}
}
});
});
//预览图事件
function readURL(preFile,markId){
var reader = new FileReader();
reader.readAsDataURL(preFile.files[0]);
reader.onload = function(e){
//循环判断为空
var preImges = document.getElementsByName("preImg");
for(var i =0;i<preImges.length;i++){
if($(preImges[i]).attr("src")==''){
$(preImges[i]).removeAttr("src");
$(preImges[i]).removeAttr("markId");
$(preImges[i]).attr("src",e.target.result);
$(preImges[i]).attr("markId",markId);
break;
}
}
}
}
//删除预览图事件
function deletePre(preId){
$("#"+preId).removeAttr("src");
$("#"+preId).attr("src",'');
var tempMark = $("#"+preId).attr("markId");
$("#"+tempMark).val('');
}
</script>
</head>
<body>
<div style="margin-left: 35%;margin-top: 10%">
<div style="margin-left:5%;margin-top: 10%">简单的照片预览与批量上传</div>
<form action="" method="post" enctype="multipart/form-data" id = "imgFile">
<table cellpadding="10px" cellspacing="10px">
<tbody>
<tr>
<td>用户名:</td>
<td><input id="userName" name = "userName" type="text"></td>
<td> </td>
</tr>
<tr>
<td>相册:</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td><img alt="相片1" src="" style="width: 100px" id="preImg_1" name ="preImg"><a href="javascript:void(0);"onclick="deletePre('preImg_1')">删除</a></td>
<td><img alt="相片2" src="" style="width: 100px" id="preImg_2" name ="preImg"><a href="javascript:void(0);"onclick="deletePre('preImg_2')">删除</a></td>
<td><img alt="相片3" src="" style="width: 100px" id="preImg_3" name ="preImg"><a href="javascript:void(0);"onclick="deletePre('preImg_3')">删除</a></td>
</tr>
</tbody>
</table>
<div style="margin-left:8%;margin-top:5%">
<input type="button" value = "选择图片" id="changeImg"> <input type="submit" value =" 提 交 ">
</div>
<div>
<span>实际提交相片的File组件</span><br>
<br><br>
<input type="file" id = "fileId_1" name="file" onchange="readURL(this,'fileId_1')">
<input type="file" id = "fileId_2" name="file" onchange="readURL(this,'fileId_2')">
<input type="file" id = "fileId_3" name="file" onchange="readURL(this,'fileId_3')">
</div>
</form>
</div>
</body>
</html>
后台代码
package com.lovo.controller;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.lovo.utils.FileUploadCheck;
@Controller
public class batchImgController {
private static Logger logger = Logger.getLogger(batchImgController.class);
@RequestMapping(value = "/batchImg.do",method = RequestMethod.GET)
public String batchImgGet(){
//get方法,处理jsp跳转前的一些验证和准备
return "batchFileUpload";
}
/**
* 图片批量提交方法
* @param userName
* @param file
* @return
*/
@RequestMapping(value = "/batchImg.do",method = RequestMethod.POST)
public String batchImgPost(@RequestParam("userName") String userName,@RequestParam("file")MultipartFile[] file ,HttpServletRequest request){
//表单基本信息
System.out.println(userName);
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/") + "fileUpload/";
//储存文件名或文件路径
List<String> imgNameList = new ArrayList<String>();
try {
for (MultipartFile img : file)
{
if(!img.isEmpty())
{
//文件重命名
Date day = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String newName = sdf.format(day)+System.currentTimeMillis()+".jpg";
//方法判定是否为图片
if(FileUploadCheck.allowUpload(img.getContentType()))
{
img.transferTo(new File(filePath+newName));
//存储文件的新名字,之后根据项目情况对文件进行入库,并把实体文件上传到FTP
imgNameList.add(newName);
}
}
}
} catch (Exception e) {
logger.error("文件上传失败");
}
return "batchFileUpload";
};
}
工具类
package com.lovo.utils;
import java.util.Arrays;
import java.util.List;
public class FileUploadCheck {
//支持的文件类型
public static final List<String> ALLOW_TYPES = Arrays.asList("image/jpg","image/jpeg","image/png","image/gif");
//校验文件类型是否是被允许的
public static boolean allowUpload(String postfix){
return ALLOW_TYPES.contains(postfix);
}
}
网友评论