1.htmlhtml
<``input
type="file" multiple="multiple" accept="image/gif, image/jpeg, image/png, image/jpg, image/bmp" />
ajax
2.JS服務器
$(document).on("change", ".upload-img input:file", function() {app
var fileId = $(this).attr("id");
var t_files = this.files;
var imglength = $("#view_" + fileId).parent().parent().find(".upload-img").length;dom
if (imglength==1) {
if (t_files.length > 5) {
new Message().showMsg("最多選擇五張圖片");
return false;
} else if (t_files.length < 1) {
new Message().showMsg("至少選擇一張圖片");
return false;
}
}else if(t_files.length+imglength>6) {
new Message().showMsg('最多再選擇'+ (6-parseInt(imglength)) +'張圖片');
return false;
}
var data = new FormData();
for (var i=0;i<t_files.length;i++){
data.append('file',t_files[i]);
data.append('randomCode',fileId+i);
data.append('upDir','comment')
}
// for(var pair of data.entries()){
// console.log(pair);
// }
// console.log(JSON.stringify(data));
$.ajax({
url : '${pageContext.request.contextPath}/file/multipleCommentImageUpload', //用於文件上傳的服務器端請求地址
type : 'post',
processData: false, // 告訴jQuery不要去處理髮送的數據
contentType: false, // 告訴jQuery不要去設置Content-Type請求頭
data:data,
cache: false
}).done(function(data,status){
var dataObj = jQuery.parseJSON(data);
if(dataObj.state == -1){
new Message().showMsg("上傳圖片出錯");
}else{
var imgs = dataObj.imgs;
for (var i=0;i<imgs.length;i++) {
var imgUrl = imgs[i].imageUrl;
var imglength = $("#view_" + fileId).parent().parent().find(".upload-img").length
if ( imglength < 5) {
$("#view_" + fileId).parent().after('<div class="upload-img"><img src="' + imgUrl + '" alt="" class="upload_left" rotation-num="0"/></div>');
$("#view_" + fileId).parent().nextAll().find('span').eq(0).text(parseInt($("#view_" + fileId).parent().nextAll().find('span').eq(0).text())+1);
$("#view_" + fileId).parent().nextAll().find('span').eq(1).text(5-parseInt($("#view_" + fileId).parent().nextAll().find('span').eq(0).text()));
}else{
$("#view_" + fileId).attr('src',imgUrl);
$("#view_" + fileId).nextAll().find('input').hide();
$("#view_" + fileId).parent().nextAll().remove('p');
}ide
}
}
}).fail(function (res) {
//console.log("error")
})post
上面第19行表明初始化formdata對象,其有兩種建立方法,對於使用html2來講使用該方式來建立,使用html1來講能夠使用 var data = new FormData(document.getElementById("#formfile");兩種建立方式基本沒有區別;第22-23行是能夠給formdata添加其餘屬性的,,按需選擇,21行是添加文件必需要寫的.ajax部分 32 33行是必需要設置的
ui
3.Java代碼部分:this
public void multipleCommentImageUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = false)List<MultipartFile> files) {
response.setContentType("text/html;charset=utf-8");
UserSession user = WebUtil.getSessionUser(request);
for (MultipartFile file:files) {
String fileName = file.getOriginalFilename(); //獲取文件名
}
UploadMessage message = new UploadMessage();
Map map1 = new HashMap();url
try {
Map<String,Object> map = this.multipleUpload(request, files);
};
protected Map<String,Object> multipleUpload(HttpServletRequest request, List<MultipartFile> files) throws IllegalStateException, IOException {
Map<String,Object> map =new HashMap();
for(MultipartFile file:files) {
if (file == null) {
map.put("status",-1);
map.put("statusInfo","上傳參數不能爲空");
return map;
}
}
//建立一個通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判斷 request 是否有文件上傳,即多部分請求
if (multipartResolver.isMultipart(request)) {
//轉換成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Enumeration params = multiRequest.getParameterNames();
String upDir = null;
//得到formdata對象中自定義的一些屬性,是枚舉類型
while (params.hasMoreElements()) {
String name = (String)params.nextElement();
upDir = multiRequest.getParameter("upDir");
}
//取得request中的全部文件名
Iterator<String> iter = multiRequest.getFileNames();
List<Map> list = new ArrayList<>();
MultiValueMap<String, MultipartFile> multiValueMap = multiRequest.getMultiFileMap();
List<MultipartFile> fileList = multiValueMap.get("file");
for (MultipartFile file:fileList){
//這裏上傳多張圖片
StringBuffer url = new StringBuffer("");
Map<String,String> map1 = new HashMap<>();
if (file != null) {
//取得當前上傳文件的文件名稱
String originalFilename = file.getOriginalFilename();
//若是名稱不爲「」,說明該文件存在,不然說明該文件不存在
if (originalFilename != null && originalFilename.trim() != "") {
String suffix = "";
if (originalFilename.indexOf(".") > -1) {
suffix = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
}
if (notImageFormat(suffix)) {
map.put("statusInfo",imageFomat);
return map;
}
if (isPassSize(file.getSize())) {
map.put("stateInfo",imageSize);
return map;
}
//重命名上傳後的文件名
String fileName = idWorker.nextId() + suffix;
String dir = DateTimeUtil.formatDateTime("yy/MM/dd");
if (!StringUtils.isBlank(upDir)){
url.append("/").append( upDir);
}
url.append("/").append(dir).append("/");
//定義上傳路徑 String path = ParamUtil.imageServiceRealPath + url; //上傳圖片 imageUploadService.uploadImage(path, fileName, file.getInputStream()); String allUrl = url + fileName; map1.put("imagePath",url.toString()); map1.put("imageName",fileName); map1.put("imageUrl",ParamUtil.imageServicePath + allUrl); list.add(map1); } } } map.put("status",0); map.put("statusInfo","success"); map.put("imgs",list); } return map; }