效果預覽:
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);
}
}
}
}
}
}