利用ajaxfileupload.js 实现文件上传写入,注意对ajaxfileupload.js 问题的修改,见 js ajaxfileupload.js 上传报错的解决方法
1、前端jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"2、java后端:
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="../resource/js/jquery/jquery-2.2.3.js" type="text/javascript"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>
<script type="text/javascript">
function setImg2(obj){ //用于进行图片上传,返回地址
var f=$(obj).val();
if(f == null || f ==undefined || f == ''){
return false;
}else if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f))
{
alertLayel("类型必须是图片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
$(obj).val('');
return false;
}else{
//批量上传图片
$.ajaxFileUpload({
url:"../upload/uploadImgList",//需要链接到服务器地址
secureuri:false,
fileElementId:"logoFile2",//文件选择框的id属性 ,//文件选择框的id属性
dataType: 'json', //json
contentType: false, //不可缺
processData: false, //不可缺
success: function (data){
debugger;
if(data!=null){
$.each(data,function(i,url){
//拼接图片列表
var id = $('#detailImgs li:last').attr('id');
id = id.substr(1);
id = parseInt(id) + 1;
var ids=id;
id = 'P'+id;
var a_hidden="<li id='"+ id +"'><input type='hidden' value='"+url+"' name='imgs'>";
var img_html="<img height='50px' width='50px' src='"+url+"' onclick='showOriginal(this)' original='"+url+"'>";
var a_html="<a href='javascript:void(0);' onclick='delespan1("+ids+")'>删除</a>";
var li_html="</li>";
$('#detailImgs').append(a_hidden+img_html+a_html+li_html);
});
}else{
alert("上传失败");
$("#url").val("");
$(obj).val('');
}
},
error:function(XMLHttpRequest, textStatus, errorThrown){
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
alert("上传失败,请检查网络后重试");
$("#url").val("");
$(obj).val('');
}
});
}
}
//上传之后如果感觉有张上传错了,想删除怎么办:
function delespan1(id){
$('#P'+id).remove();
}
</script>
</head>
<body>
<!-- 多图批量上传 -->
<a href="javascript:void(0);" class="btn_addPic">
<span id="imgTitle">多图批量上传:</span> </br>
<input type="file" name="file" id="logoFile2" onchange="setImg2(this);" class="selectedLogoImgId"
accept="image/jpg,image/jpeg,image/png,image/bmp" multiple/>
</a>
<div class="cp-img" id="logoImgDiv6">
<ul id="detailImgs" style="overflow: hidden;">
<li style="display:none;" id="P0">
</ul>
<span id="hiddenss1"></span>
</div>
</body>
</html>
@RequestMapping("uploadImgList")
@ResponseBody
public String uploadPictureList(
@RequestParam(value="file",required=false)MultipartFile[] file,
HttpServletRequest request) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
File targetFile=null;
String msg="";//返回存储路径
int code=1;
List imgList=new ArrayList();
if (file!=null && file.length>0) {
for (int i = 0; i < file.length; i++) {
MultipartFile entity = file[i];
String name = entity.getOriginalFilename();
String fileName=file[i].getOriginalFilename();//获取文件名加后缀
if(fileName!=null&&fileName!=""){
String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";//存储路径
String path = request.getSession().getServletContext().getRealPath("blobform/imgs"); //文件存储位置
String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名
//先判断文件是否存在
String fileAdd =new SimpleDateFormat("yyyyMMdd").format(new Date());
File file1 =new File(path+"/"+fileAdd);
//如果文件夹不存在则创建
if(!file1 .exists() && !file1 .isDirectory()){
file1 .mkdir();
}
targetFile = new File(file1, fileName);
try {
file[i].transferTo(targetFile);
// msg=returnUrl+fileAdd+"/"+fileName;
msg="imgs/"+fileAdd+"/"+fileName;
imgList.add(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return objectMapper.writeValueAsString(imgList);
}