1. Import resources
2. JSP code
<div> <label><span >*</span>Project name: </label> <div> <input type="text" value="${proName }" placeholder="" id="" name="proName" readonly="readonly"> </div> </div> <div> <label>Thumbnail: </label> <div> <div> <div> <div> <div id="fileList"></div> <div> <div id="filePicker">Select picture</div> <button id="btn-star">Start upload</button> </div> </div> </div> <div> <label><span >*</span>Project invoice upload: </label> <div> <div> <div> <div> <div id="dndArea"> <div id="filePicker-2"></div> <p>Or drag the photo here, you can select up to 300 photos in a single time</p> </div> </div> <div style="display:none;"> <div> <span>0%</span> <span></span> </div> <div> <div> <div> <div> id="filePicker2"></div> <div> <div> Start uploading</div> </div> </div> </div> </div> </div> </div> <div> <button onClick="article_add('','invoiceVo/save?&projectId=${projectId}&invoiceScan=','10001');" type="button"> <i></i> Save</button> </div> </div> </div> 3. Js code
<script type="text/javascript"> var imagePath=null; function article_save() { alert("The bullet layer will be automatically closed when refreshing the parent."); window.parent.location.reload(); } /*Project Invoice-Add*/ function article_add(title, url, w, h) { if(imagePath){ var index = layer.open({ type : 2, title : title, content : url+imagePath }); layer.full(index); }else{alert("No image upload, please upload image first");} } $(function() { $('.skin-minimal input').iCheck({ checkboxClass : 'icheckbox-blue', radioClass : 'iradio-blue', increaseArea : '20%' }); $list = $("#fileList"), $btn = $("#btn-star"), state = "pending", uploader; var uploader = WebUploader.create({ auto : true, swf : 'lib/webuploader/0.1.5/Uploader.swf',// swf file path// file receiving server. server: 'lib/webuploader/0.1.5/server/fileupload.php', // File receiving server. // Select the file button. Optional. // Create internally according to the current run, which may be an input element or flash. pick : '#filePicker', // Image is not compressed. By default, if it is jpeg, it will compress it and upload it again before uploading! resize : false, // Only image files are allowed. accept : { title : 'Images', extensions : 'gif,jpg,jpeg,bmp,png', mimeTypes : 'image/*' } }); // When a file is added to the queue, uploader .on( 'fileQueued', function(file) { var $li = $('<div id="' + file.id + '">' + '<div><img></div>' + '<div>' + file.name + '</div>' + '<p>wait for upload...</p>' + '</div>'), $img = $li.find('img'); $list.append($li); // Create thumbnail// If it is a non-image file, you can not call this method. // thumbnailWidth x thumbnailHeight is 100 x 100 uploader.makeThumb(file, function(error, src) { if (error) { $img.replaceWith('<span>cannot preview</span>'); return; } $img.attr('src', src); }, thumbnailWidth, thumbnailHeight); }); // Create a progress bar in real time during file uploading. uploader .on( 'uploadProgress', function(file, percentage) { var $li = $('#' + file.id), $percent = $li .find('.progress-box .sr-only'); // Avoid repeated creation of if (!$percent.length) { $percent = $( '<div><span><span></span></span></div>') .appendTo($li).find('.sr-only'); } $li.find(".state").text("uploading"); $percent.css('width', percentage * 100 + '%'); }); // The file is uploaded successfully, add a successful class to the item, and mark the upload success with the style. uploader.on('uploadSuccess', function(file) { $('#' + file.id).addClass('upload-state-success') .find(".state").text("uploaded"); }); // File upload failed, and an error was displayed. uploader.on('uploadError', function(file) { $('#' + file.id).addClass('upload-state-error').find(".state") .text("upload error"); }); // After the upload is completed, it is successful or failed, delete the progress bar first. uploader.on('uploadComplete', function(file) { $('#' + file.id).find('.progress-box').fadeOut(); }); uploader.on('all', function(type) { if (type === 'startUpload') { state = 'uploading'; } else if (type === 'stopUpload') { state = 'paused'; } else if (type === 'uploadFinished') { state = 'done'; } if (state === 'uploading') { $btn.text('pause upload'); } else { $btn.text('Start upload'); } }); $btn.on('click', function() { if (state === 'uploading') { uploader.stop(); } else { uploader.upload(); } }); }); (function($) { // Initialization starts when domReady { var $wrap = $('.uploader-list-container'), // Picture container $queue = $('<ul></ul>').appendTo( $wrap.find('.queueList')), // Status bar, including progress and control button $statusBar = $wrap.find('.statusBar'), // Overall file selection information. $info = $statusBar.find('.info'), // Upload button $upload = $wrap.find('.uploadBtn'), // Contents before the file are not selected. $placeHolder = $wrap.find('.placeholder'), $progress = $statusBar.find('.progress').hide(), // Number of files added fileCount = 0, // Total size of files added fileSize = 0, // Optimize retina, under retina, this value is 2 ratio = window.devicePixelRatio || 1, // Thumbnail size thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio, // There may be pedding, ready, uploading, confirm, done. state = 'pedding', // All files progress information, the key is file id percentages = {}, // Determine whether the browser supports image base64 isSupportBase64 = (function() { var data = new Image(); var support = true; data.onload = data.onerror = function() { if (this.width != 1 || this.height != 1) { support = false; } } data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAQABAAACAUwAOw=="; return support; })(), // Check whether flash has been installed and detect the version of flash flashVersion = (function() { var version; try { version = navigator.plugins['Shockwave Flash']; version = version.description; } catch (ex) { try { version = new ActiveXObject( 'ShockwaveFlash.ShockwaveFlash') .GetVariable('$version'); } catch (ex2) { version = '0.0'; } } version = version.match(//d+/g); return parseFloat(version[0] + '.' + version[1], 10); })(), supportTransition = (function() { var s = document.createElement('p').style, r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s; s = null; return r; })(), // WebUploader instance uploader; if (!WebUploader.Uploader.support('flash') && WebUploader.browser.ie) { // flash is installed but the version is too low. if (flashVersion) { (function(container) { window['expressinstallcallback'] = function(state) { switch (state) { case 'Download.Cancelled': alert('You canceled the update!') break; case 'Download.Failed': alert('Installation failed') break; default: alert('Installation has been successful, please refresh!'); break; } delete window['expressinstallcallback']; }; var swf = 'expressInstall.swf'; // insert flash object var html = '<object type="application/' + 'x-shockwave-flash" data="' + swf + '" '; if (WebUploader.browser.ie) { html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '; } html += 'width="100%" style="outline:0">' + '<param name="movie" value="' + swf + '" />' + '<param name="wmode" value="transparent" />' + '<param name="wmode" value="transparent" />' + '<param name="wmode" value="transparent" />' + '<param name="wmode" value="transparent" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>'; container.html(html); })($wrap); // It's not stable at all. } else { $wrap .html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank"><img src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>'); } return; } else if (!WebUploader.Uploader.support()) { alert('Web Uploader does not support your browser!'); return; } // Instantiated uploader = WebUploader.create({ pick : { id : '#filePicker-2', label : 'click to select picture' }, formData : { uid : 123 }, dnd : '#dndArea', paste : '#uploader', swf : 'lib/webuploader/0.1.5/Uploader.swf', chunked : false, chunkSize : 512 * 1024, server : 'invoiceVo/news_uploder?&projectId=${projectId}', // runtimeOrder: 'flash', // accept: { // title: 'Images', // extensions: 'gif,jpg,jpeg,bmp,png', // mimeTypes: 'image/*' // }, // Disable the global drag function. This will not appear when the image is dragged into the page, turn on the image. disableGlobalDnd : true, fileNumLimit : 300, fileSizeLimit : 200 * 1024 * 1024, // 200 M fileSingleSizeLimit : 50 * 1024 * 1024 // 50 M }); // The js, txt file is not accepted when dragging. uploader.on('dndAccept', function(items) { var denied = false, len = items.length, i = 0, // Modify js type unAllowed = 'text/plain;application/javascript '; for (; i < len; i++) { // If in the list (~unAllowed.indexOf(items[i].type)) { denied = true; break; } } return !denied; }); uploader.on('dialogOpen', function() { console.log('here'); }); // uploader.on('filesQueued', function() { // uploader.sort(function( a, b ) { // if ( a.name < b.name ) // return -1; // if ( a.name > b.name ) // return 1; // return 0; // }); // }); // add "add file" button, /* uploader.addButton({ id : '#filePicker2', label : 'continue to add' }); */ uploader.on('ready', function() { window.uploader = uploader; }); // Execute when a file is added, the function of the view is responsible for creating the function addFile(file) { var $li = $('<li id="' + file.id + '">' + '<p>' + file.name + '</p>' + '<p></p>' + '<p><span></span></p>' + '</li>'), $btns = $( '<div>' + '<span>Delete</span>' + '<span>Rotate to the right</span>' + '<span>Rotate to the left</span></div>') .appendTo($li), $prgress = $li .find('p.progress span'), $wrap = $li .find('p.imgWrap'), $info = $('<p></p>'), showError = function(code) { switch (code) { case 'exceed_size': text = 'File size exceeds'; break; case 'interrupt': text = 'Upload pause'; break; default: text = 'Upload failed, please try again'; break; } $info.text(text).appendTo($li); }; if (file.getStatus() === 'invalid') { showError(file.statusText); } else { // @todo lazyload $wrap.text('Preview'); uploader .makeThumb( file, function(error, src) { var img; if (error) { $wrap.text('can't preview'); return; } if (isSupportBase64) { img = $('<img src="'+src+'">'); $wrap.empty().append(img); } else { $ .ajax( 'lib/webuploader/0.1.5/server/preview.php', { method : 'POST', data : src, dataType : 'json' }) .done( function( response) { if (response.result) { img = $('<img src="'+response.result+'">'); $wrap .empty() .append( img); } else { $wrap .text("preview error"); } }); } }, thumbnailWidth, thumbnailHeight); percentages[file.id] = [ file.size, 0 ]; file.rotation = 0; } file.on('statuschange', function(cur, prev) { if (prev === 'progress') { $prgress.hide().width(0); } else if (prev === 'queued') { $li.off('mouseenter mouseleave'); $btns.remove(); } // Success if (cur === 'error' || cur === 'invalid') { console.log(file.statusText); showError(file.statusText); percentages[file.id][1] = 1; } else if (cur === 'interrupt') { console.log(file.statusText); showError(file.statusText); percentages[file.id][1] = 1; } else if (cur === 'interrupt') { showError('interrupt'); } else if (cur === 'queued') { percentages[file.id][1] = 0; } else if (cur === 'progress') { $info.remove(); $prgress.css('display', 'block'); } else if (cur === 'complete') { $li.append('<span></span>'); } $li.removeClass('state-' + prev).addClass('state-' + cur); }); $li.on('mouseenter', function() { $btns.stop().animate({ height : 30 }); }); $li.on('mouseleave', function() { $btns.stop().animate({ height : 0 }); }); $btns .on( 'click', 'span', function() { var index = $(this).index(), deg; switch (index) { case 0: uploader.removeFile(file); return; case 1: file.rotation += 90; break; case 2: file.rotation -= 90; break; } if (supportTransition) { deg = 'rotate(' + file.rotation + 'deg)'; $wrap.css({ '-webkit-transform' : deg, '-mos-transform' : deg, '-o-transform' : deg, 'transform' : deg }); } else { $wrap .css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')'); } }); $li.appendTo($queue); } // Responsible for the destruction of the view function removeFile(file) { var $li = $('#' + file.id); delete percentages[file.id]; updateTotalProgress(); $li.off().find('.file-panel').off().end().remove(); } function updateTotalProgress() { var loaded = 0, total = 0, spans = $progress.children(), percent; $.each(percentages, function(k, v) { total += v[0]; loaded += v[0] * v[1]; }); percent = total ? loaded / total : 0; spans.eq(0).text(Math.round(percent * 100) + '%'); spans.eq(1).css('width', Math.round(percent * 100) + '%'); updateStatus(); } function updateStatus() { var text = '', stats; if (state === 'ready') { text = 'Select' + fileCount + 'Images, total ' + WebUploader.formatSize(fileSize) + '. '; } else if (state === 'confirm') { stats = uploader.getStats(); if (stats.uploadFailNum) { text = 'Uploaded successfully' + stats.successNum + 'Photo to XX album, ' + stats.uploadFailNum + 'Photo upload failed, <a href="#" rel="external nofollow" rel="external nofollow" >Re-upload</a> failed picture or <a href="#" rel="external nofollow" rel="external nofollow" >Ignored</a>' } } else { stats = uploader.getStats(); text = 'Total' + fileCount + 'Zhang (' + WebUploader.formatSize(fileSize) + '), uploaded' + stats.successNum + 'Zhang'; if (stats.uploadFailNum) { text += ', failed' + stats.uploadFailNum + 'Zhang'; } } $info.html(text); } function setState(val) { var file, stats; if (val === state) { return; } $upload.removeClass('state-' + state); $upload.addClass('state-' + val); state = val; switch (state) { case 'pedding': $placeHolder.removeClass('element-invisible'); $queue.hide(); $statusBar.addClass('element-invisible'); uploader.refresh(); break; case 'ready': $placeHolder.addClass('element-invisible'); $('#filePicker2').removeClass('element-invisible'); $queue.show(); $statusBar.removeClass('element-invisible'); uploader.refresh(); break; case 'uploading': $('#filePicker2').addClass('element-invisible'); $progress.show(); $upload.text('stop upload'); break; case 'paused': $progress.show(); $upload.text('continue upload'); break; case 'confirm': $progress.hide(); $('#filePicker2').removeClass('element-invisible'); $upload.text('start upload'); stats = uploader.getStats(); if (stats.successNum && !stats.uploadFailNum) { setState('finish'); return; } break; case 'finish': stats = uploader.getStats(); if (stats.successNum) { alert('uploaded successfully'); } else { // There is no successful picture, reset state = 'done'; location.reload(); } break; } updateStatus(); } uploader.onUploadProgress = function(file, percentage) { var $li = $('#' + file.id), $percent = $li .find('.progress span'); $percent.css('width', percentage * 100 + '%'); percentages[file.id][1] = percentage; updateTotalProgress(); }; uploader.onFileQueued = function(file) { fileCount++; fileSize += file.size; if (fileCount === 1) { $placeHolder.addClass('element-invisible'); $statusBar.show(); } addFile(file); setState('ready'); updateTotalProgress(); }; uploader.onFileDequeued = function(file) { fileCount--; fileSize -= file.size; if (!fileCount) { setState('pedding'); } removeFile(file); updateTotalProgress(); }; /*get the data returned by the server*/ uploader.on('uploadSuccess', function(file, response) { alert(response.status); if (response.status == "success") { imagePath =response.filePath; alert("File save path: " + response.filePath); } else if (response.status == "error") alert(response.error); }); uploader.on('all', function(type) { var stats; //alert(type); switch (type) { case 'uploadFinished': setState('confirm'); break; case 'startUpload': setState('uploading'); break; case 'stopUpload': setState('paused'); break; } }); uploader.onError = function(code) { alert('Eroor: ' + code); }; $upload.on('click', function() { if ($(this).hasClass('disabled')) { return false; } if (state === 'ready') { //Click the upload button to enter the ready state. uploader.upload(); //Start upload} else if (state === 'paused') { uploader.upload(); } else if (state === 'uploading') { uploader.stop(); } }); $info.on('click', '.retry', function() { uploader.retry(); }); $info.on('click', '.ignore', function() { alert('todo'); }); $upload.addClass('state-' + state); updateTotalProgress(); }); })(jQuery); </script> Notice:
4. Controller code
/** * Jump to the page where the invoice is uploaded* @param proName * @param map * @return */ @RequestMapping(value = "/upload" ) public String invoiceUpload(String proName,Long id,Map<String, Object> map){ map.put("proName", proName); projectService.getProject(id); map.put("projectId", id); return "project/invoiceUpload"; } /** * Upload the invoice and save the database* @param file * @param request * @param response * @return */ @ResponseBody @RequestMapping(value = "/news_uploder", method ={RequestMethod.POST,RequestMethod.GET}, produces = "application/json; charset=utf-8") public JSONObject uploader(@RequestParam MultipartFile[] file,Long projectId,HttpServletRequest request,HttpServletResponse response){ String flag=null; JSONObject jsonObject = new JSONObject(); try { WebuploaderUtil webuploaderUtil=new WebuploaderUtil(); webuploaderUtil.upload(file[0], "upload/invoice/", request); flag=webuploaderUtil.getFileName(); jsonObject.put("filePath", flag); jsonObject.put("status", "success"); } catch (Exception e) { e.printStackTrace(); } return jsonObject; } 5. Tool class package com.softjx.util;/** *Project Name: QDLIMAP *File Name: WebuploaderUtil.java *Package Name: com.ltmap.platform.cms.util *Date: April 13, 2017 at 6:30:45 pm *Copyright (c) 2017,[email protected] All Rights Reserved. */ import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.springframework.web.multipart.MultipartFile; /** *Title: WebuploaderUtil<br/> *Description: *@Company: Litu Hi-Tech<br/> *@author: Liu Yunsheng*@version: v1.0 *@since: JDK 1.8.0_40 *@Date: April 13, 2017 at 6:30:45 pm <br/> */ public class WebuploaderUtil { private String allowSuffix = "jpg,png,gif,jpeg";//Allow file format private long allowSize = 2L;//Allow file size private String fileName; private String[] fileNames; public String getAllowSuffix() { return allowSuffix; } public void setAllowSuffix(String allowSuffix) { this.allowSuffix = allowSuffix; } public long getAllowSize() { return allowSize*1024*1024; } public void setAllowSize(long allowSize) { this.allowSize = allowSize; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String[] getFileNames() { return fileNames; } public void setFileNames(String[] fileNames) { this.fileNames = fileNames; } /** * * @Title: getFileNameNew * @Description: TODO * @param: @return * @return: String * @author: Liu Yunsheng* @Date: April 14, 2017 at 10:17:35 am * @throws */ private String getFileNameNew(){ SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS"); return fmt.format(new Date()); } /** * * @Title: uploads * @Description: TODO * @param: @param files * @param: @param destDir * @param: @param request * @param: @throws Exception * @return: void * @author: Liu Yunsheng* @Date: April 14, 2017 at 10:17:14 am * @throws */ public void uploads(MultipartFile[] files, String destDir,HttpServletRequest request) throws Exception { String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; try { fileNames = new String[files.length]; int index = 0; for (MultipartFile file : files) { String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); int length = getAllowSuffix().indexOf(suffix); if(length == -1){ throw new Exception("Please upload the file in the allowed format"); } if(file.getSize() > getAllowSize()){ throw new Exception("The file size you uploaded is out of range"); } String realPath = request.getSession().getServletContext().getRealPath("/"); File destFile = new File(realPath+destDir); if(!destFile.exists()){ destFile.mkdir(); } String fileNameNew = getFileNameNew()+"."+suffix;// File f = new File(destFile.getAbsoluteFile()+"//"+fileNameNew); file.transferTo(f); f.createNewFile(); fileNames[index++] =basePath+destDir+fileNameNew; } } catch (Exception e) { throw e; } } /** * * @Title: upload * @Description: TODO * @param: @param file * @param: @param destDir * @param: @param request * @param: @throws Exception * @return: void * @author: Liu Yunsheng* @Date: April 14, 2017 at 10:16:16 am * @throws */ public void upload(MultipartFile file, String destDir,HttpServletRequest request) throws Exception { String path = request.getContextPath(); //http://localhost:8088/huahang String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; try { String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); int length = getAllowSuffix().indexOf(suffix); if(length == -1){ throw new Exception("Please upload files in the allowed format"); } if(file.getSize() > getAllowSize()){ throw new Exception("The file size you uploaded has exceeded the range"); } String realPath = request.getSession().getServletContext().getRealPath("/")+"/"; File destFile = new File(realPath+destDir); if(!destFile.exists()){ destFile.mkdirs(); } String fileNameNew = getFileNameNew()+"."+suffix; File f = new File(destFile.getAbsoluteFile()+"/"+fileNameNew); file.transferTo(f); f.createNewFile(); //Include the full path of the website http://localhost:8080/QDLIMAP/upload/user/20170414104142667.png //fileName = basePath+destDir+fileNameNew; //Return the relative path upload/user/20170414104142667.png fileName = destDir+fileNameNew; } catch (Exception e) { throw e; } } }Summarize
The above is the webuploader that I introduced to you. The image batch upload function is equipped with example code. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!