ajaxuploadiy 多檔案上傳
jsp頁面:
<table>
<tr>
<td>上傳圖片:</td>
<td>
<input type="button" value="新增圖片" onclick="createInput('fileQueue');" />
<input type="button" name="tijiao" value="上傳" onclick="upload()">
<div id="fileQueue"></div>
<br/><div id="imageDiv"></div>
<input type="hidden" value="${deptInfo.images}" name="images" id="images"/>
</td>
</tr></table>
js程式碼:
<script type="text/javascript">
$(document).ready(function(){
});
function upload(){
var uplist = $("input[name^=uploads]");
for (var i=0; i< uplist.length; i++){
if(uplist[i].value){
$.ajaxFileUpload(
{
url: '${pageContext.request.contextPath}/dept/upload', //用於檔案上傳的伺服器端請求地址
secureuri: false, //是否需要安全協議,一般設定為false
fileElementId: uplist[i].id, //檔案上傳域的ID
dataType: 'json', //返回值型別 一般設定為json
success: function (data) //伺服器成功響應處理函式
{
if (typeof (data.result) != 'undefined') {
if(data.result == ('success')){
var vv = (data.imgurl).split('|');
var imageUrl = vv[0].split("/")[2];
var html="<img onclick='showdiv(\""+imageUrl+"\")' name='"+imageUrl+"' id='"+imageUrl+"' style='width:100px;height:100px;' src='${pageContext.request.contextPath}/"+vv[0]+"'/>";
html += "<a class='"+imageUrl+"' href='javascript:void();' onclick=\"deleteImage(this,'"+imageUrl+"')\">刪除</a>";
$("#imageDiv").append(html);
var images;
if($("#images").val().length != 0){
var images = $("#images").val()+";"+imageUrl;
}else{
images = imageUrl;
}
$("#images").val(images);
}else{
alert("上傳失敗!");
}
}
$("#fileQueue").empty();
},
error: function (data, status, e)//伺服器響應失敗處理函式
{
alert(e);
}
}
)
}
}
}
//刪除圖片
function deleteImage(deleteA,imageUrl){
$.ajax({
type:"post",
async:false,
cache:false,
data:"imageUrl="+imageUrl,
success:function(msg){
if(msg!=''){
alert(msg);
$(deleteA).remove();
var thisNode=document.getElementsByName(imageUrl);
for(var i=0;i<thisNode.length;i++){
document.getElementById("fileQueue").removeChild(thisNode[i]);
}
//修改images的值
var image = "";
$.each($("#imageDiv").find("img"),function(i,img){
image += $(img).attr("name")+";";
});
$("#images").val(image.substring(0,image.length-1));
}
},
error:function(){
$.messager.alert('警告','系統異常!','error');
}
});
}
var count = 1;
/**
* 生成多附件上傳框
*/
function createInput(parentId){
count++;
var str = '<div name="div" >'+
' '+ '<br/><input type="file" contentEditable="false" id="uploads' + count + '' +
'" name="uploads'+ count +'" value="" style="width: 220px"/><input type="button" value="刪除" onclick="removeInput(event)" />'+'</div>';
$("#fileQueue").append(str);
}
/**
* 刪除多附件刪除框
*/
function removeInput(evt, parentId){
var parentId = 'fileQueue';
var el = evt.target == null ? evt.srcElement : evt.target;
var div = el.parentNode;
var cont = document.getElementById(parentId);
if(cont.removeChild(div) == null){
return false;
}
return true;
}
</script>
java後臺控制器:
/**
*
* @Title: uploadImage
* @Description: 上傳網點圖片
* @param request
* @param response
* @throws IOException
* @return void
* @author zgj
* @date 2016年3月21日 下午2:53:06
*/
@RequestMapping(value="/upload")
public void uploadImage(HttpServletRequest request,HttpServletResponse response) throws IOException{
String responseStr = "";
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 獲取前臺傳值
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
String configPath = "upload/images/";
String ctxPath = request.getSession().getServletContext().getRealPath("/");
ctxPath += configPath;
// 建立資料夾
File file = new File(ctxPath);
if (!file.exists()) {
file.mkdirs();
}
String fileName = null;
String res = "";
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 上傳檔名
MultipartFile mf = entity.getValue();
fileName = mf.getOriginalFilename();
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
responseStr = configPath + newFileName + "|" + fileName;
res = "{result:'success',imgurl:'" + responseStr + "'}";
File uploadFile = new File(ctxPath + newFileName);
try {
FileCopyUtils.copy(mf.getBytes(), uploadFile);
} catch (IOException e) {
responseStr = "fail";
res = "{result:'" + responseStr + "'}";
e.printStackTrace();
}
}
response.setHeader("Content-type", "text/html;charset=UTF-8");
// 這句話的意思,是告訴servlet用UTF-8轉碼,而不是用預設的ISO8859
response.setCharacterEncoding("UTF-8");
response.getWriter().write(res);
}
ps:js檔案見資源下載~~