效果预览:
html:
<div class="inputFile">
<input type="file" name="photo" id="photo" "readPic(this)" <#if readonly1?exists && readonly1 == "true">disabled</#if>/> <span>+</span>
<img id="img1" src="" alt="" class="comparison-screen">
<input type="hidden" name="comparePhotoStr" id="comparePhotoStr" />
<i class="close" onclick="closePic(this)"> </i>
</div>
js:
// 读取图片
function readPic(file){
var photoName = $(file).attr("name");
var files = file.files[0];
if(files != '' && files != undefined){
$(file).siblings('i').css('display','block')
if($(file).next().next().attr('src') == ''){
var html = '<div class="inputFile">'+
'<input name=\"'+ photoName +'\" type="file" "readPic(this)" title=" " value="">'+
'<span >+</span>'+
'<img src="" alt="" class="comparison-screen">'+
'<i class="close" "closePic(this)"> </i>'+
'</div>';
$(file).parent('div').after(html);
}
$(file).siblings('img').prop('src',window.URL.createObjectURL(files));
}
}
// 删除图片
function closePic(that){
window.event? window.event.cancelBubble = true : e.stopPropagation();
if($(that).parent('div').parent('td').find('div').length > 1){
$(that).parent('div').remove();
}else{
$(that).siblings('input').val('');
$(that).siblings('img').prop('src',' ')
}
}
//上传图片及表单:
function saveCase(caState) {
if (!validateDigital()) {
return;
}
var count = 0;
$('input[name="photo"]').each(function( index ) {
count ++;
});
if(count != 1){
$("#comparePhotoStr").val("on");
}
count = 0;
$('input[name="photo2"]').each(function( index ) {
count ++;
});
if(count != 1){
$("#backPhotoStr").val("on");
}
//$("#formData").submit();
$("#caState").val(caState);
var formData = new FormData($('#formData')[0]);
var AjaxURL = "saveCa.html";
$.ajax({
type : "POST",
dataType : "json",
url : AjaxURL + "?caState=" + caState,
async: false,
cache: false,
contentType: false,
processData: false,
data : formData,
success : function(data) {
if (typeof (data.message) != 'undefined'
&& data.message != '') {
alert(data.message);
} else {
location.href = "caListView.html";
}
},
error : function(data) {
alert("error:" + data.responseText);
}
});
}
JAVA:
@RequestMapping(value = "/saveCa.html")
@ResponseBody
public Map<String, Object> saveCase(HttpServletRequest request,@ModelAttribute("pojo")Ca ca1,@RequestParam(value = "photo",required = false) MultipartFile[] comparePhotoFiles,@RequestParam(value = "photo2",required = false) MultipartFile[] backPhotoFiles){
Map<String, Object> modelMap = new HashMap<String, Object>();
ServletContext servletContext = request.getSession().getServletContext();//获取ServletContext的对象 代表当前WEB应用
String realPath = servletContext.getRealPath("/material");//上传图片的真实路径
String type = "insert";
if(ca1.getId() != null && !"".equals(ca1.getId())){
type = "update";
}
if("insert".equals(type)){
File sysTempDir = new File(System.getProperty("java.io.tmpdir"));
if(comparePhotoFiles.length <= 1){//前台传了一个空图片
modelMap.put("message","请上传图片");
return modelMap;
}
for (MultipartFile comparePhotoFile : comparePhotoFiles) {
CommonsMultipartFile cf= (CommonsMultipartFile)comparePhotoFile; //获取本地存储路径
DiskFileItem cfi = (DiskFileItem)cf.getFileItem();
InputStream in= comparePhotoFile.getInputStream();
if(!"".equals(cfi.getName())){
String compathTempPath = sysTempDir.getAbsolutePath()+"\\"+cfi.getName();
OutputStream out=new FileOutputStream(compathTempPath);//指定输出流的位置;
byte []buffer =new byte[1024];
int len=0;
while((len=in.read(buffer))!=-1){
out.write(buffer, 0, len);
out.flush();
}
out.close();
in.close();
String photo = comparePhotoFile.getOriginalFilename();
String extension = "";
int i = photo.lastIndexOf('.');
if (i > 0) {
extension = photo.substring(i+1);
}
message += verification(compathTempPath,realPath,extension);
}
}
if(!"".equals(message)){
modelMap.put("message",message);
return modelMap;
}
for (MultipartFile comparePhotoFile : comparePhotoFiles) {
CommonsMultipartFile cf = (CommonsMultipartFile) comparePhotoFile; //获取本地存储路径
DiskFileItem cfi = (DiskFileItem) cf.getFileItem();
if(!"".equals(cfi.getName())) {
String compathTempPath = sysTempDir.getAbsolutePath() + "\\" + cfi.getName();
String photo = comparePhotoFile.getOriginalFilename();
String extension = "";
int i = photo.lastIndexOf('.');
if (i > 0) {
extension = photo.substring(i + 1);
}
if (case1.getComparePhotoStr() != null) {
//获取图片所在的目录,单案件上传时用于保存上传文件目录
String photoPath = compathTempPath;
if ("jpg".equals(extension) || "png".equals(extension)) {
Photos photos = new Photos();
photos .setId(KeyUtils.get32UUID());
photos .setCaseId(ca1.getId());
String fileName = KeyUtils.get32UUID();
photos .setPhotoId(fileName);
photos .setType("1");
//单一图片上传图片,保存到项目的material文件夹里
UploadPhotos.uploadPhotos(photoPath, realPath, fileName);
caPhotosService.insertSelective(casePhotos);
} else if ("zip".equals(extension)) {
//压缩文件,返回新图片名称
List<Map<String, String>> mapList = FileUnZip.unZip(photoPath, realPath, false);
for (Map<String, String> map : mapList) {
String newFilename = map.get("newFilename").toString();
Photos photos = new Photos();
photos.setId(KeyUtils.get32UUID());
photos.setCaseId(case1.getId());
photos.setPhotoId(newFilename);
photos.setType("1");
caPhotosService.insertSelective(photos);
}
}
}
}
}
}