How to implement asynchronous upload of images in Java webApp, first understand the following issues:
1. Upload the picture;
2. Picture upload preview;
3. Upload the image and change the address and add it to the database asynchronously;
Main content <br />This example mainly uses pure HTML front-end and JavaScript code as tools to query the code examples of demos that implement image uploading:
(1) Click on the div code to upload the image:
<div id="div1"> <input type="file" id="choose" accept="image/*" multiple > <a id="upload">Upload the image</a> <a onclick="selectphoto();">Select from the gallery</a> <a id="back">Cancel</a></div>
(2) JavaScript code
<script type="text/javascript"> //Get the input form element of the uploaded image var filechooser = document.getElementById("choose"); //Create canvas for compressing the image var canvas = document.createElement("canvas"); //Get the visual attribute of canvas var ctx = canvas.getContext('2d'); //Tile canvas var tCanvas = document.createElement("canvas"); var tctx = tCanvas.getContext("2d"); //Canvas size var maxsize = 100 * 1024; //Upload the image click event $("#upload").on("click", function() { filechooser.click(); }) .on("touchstart", function() { //Add element attribute $(this).addClass("touch"); }) .on("touchend", function() { //Remove the element attribute $(this).removeClass("touch"); }); //Element changes filechooser.onchange = function() { //If the selection is empty, return the operation if (!this.files.length) return; //Create the array of uploaded images var files = Array.prototype.slice.call(this.files); // When the number is greater than 1 picture, reverse operation, set here according to the requirements; the PC side can upload several pictures at a time, and select one on the mobile side, and only one page can be previewed. Since it is a mobile terminal, this judgment is made. if (files.length >1) { alert("Only 1 picture can be uploaded at a time"); return; } //Transfer the file array of uploaded pictures, you can just take it without traversing. files.forEach(function(file, i) { //Judge image format if (!///(?:jpeg|png|gif)/i.test(file.type)) return; var reader = new FileReader(); var li = document.createElement("li");// Get the image size var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB"; //Image preview li.innerHTML = '<div><span></span></div><div>' + size + '</div>'; //Add image preview code; $(".img-list").append($(li)); reader.onload = function() { var result = this.result; var img = new Image(); img.src = result; //The image display $(li).css("background-image", "url(" + result + ")"); //If the image size is less than 100kb, upload directly if (result.length <= maxsize) { img = null; upload(result, file.type, $(li)); return; }// After the image is loaded, compress it and then upload it if (img.complete) { callback(); } else { img.onload = callback; } function callback() { var data = compress(img); upload(data, file.type, $(li)); img = null; } }; reader.readAsDataURL(file); }); }; //The following is related to image compression; //Use canvas to compress(img) { var initSize = img.src.length; var width = img.width; var height = img.height; //If the image is larger than four megapixels, calculate the compression ratio and press the size to less than 4 million var ratio; if ((ratio = width * height / 4000000) > 1) { ratio = Math.sqrt(ratio); width /= ratio; height /= ratio; } else { ratio = 1; } canvas.width = width; canvas.height = height; //Spread the background ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); //If the image pixel is larger than 1 million, use tile to draw var count; if ((count = width * height / 1000000) > 1) { count = ~~(Math.sqrt(count) + 1); //Calculate how many tiles to be divided into // Calculate the width and height of each tiles var nw = ~~(width / count); var nh = ~~(height / count); tCanvas.width = nw; tCanvas.height = nh; for (var i = 0; i < count; i++) { for (var j = 0; j < count; j++) { tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh); ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh); } } } else { ctx.drawImage(img, 0, 0, width, height); } // Perform minimum compression var ndata = canvas.toDataURL('image/jpeg', 0.1); console.log('Before compression: ' + initSize); console.log('After compression: ' + ndata.length); console.log('Compression rate: ' + ~~(100 * (initSize - ndata.length) / initSize) + "%"); tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0; return ndata; } // Upload the picture, convert the base64 image into a binary object, stuff it into formdata to upload function upload(basestr, type, $li) { var text = window.atob(basestr.split(",")[1]); var buffer = new Uint8Array(text.length); var prime = 0, loop = null; for (var i = 0; i < text.length; i++) { buffer[i] = text.charCodeAt(i); } var blob = getBlob([buffer], type); var xhr = new XMLHttpRequest(); var formdata = getFormData(); formdata.append('upload', blob); //Asynchronous request for uploading images of the kindeditor plugin jsp page xhr.open('post', '<%=request.getContextPath()%>/kindeditor/jsp/upload_json.jsp'); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { //Return the image address on the server side var face_img=xhr.responseText; var id=$("#arId").text(); //Asynchronously add image $.ajax({ type:"POST", //Asynchronously request Struts' action class to insert the image address into the database url:"add_article_faceurl.action", dataType:"json", data:"faceurl="+face_img+"&id="+id, async:true, success: function(msg){ //Get the id value related to the image in the database and store it in the page hidden area $("#arId").text(msg); }, error: function(a){} }); } }; //Simulated upload progress display//Data sending progress, the first 50% displays the progress xhr.upload.addEventListener('progress', function(e) { if (loop) return; prime = ~~(100 * e.loaded / e.total) / 2; $li.find(".progress span").css('width', prime + "%"); if (pecent == 50) { mockProgress(); } }, false); //Search 50% of the data use simulation progress function mockProgress() { if (loop) return; loop = setInterval(function() { cement++; $li.find(".progress span").css('width', prime + "%"); if (pecent == 99) { clearInterval(loop); } }, 100); } xhr.send(formdata); } /** * Get the compatibility writing of blob objects* @param buffer * @param format * @returns {*} */ function getBlob(buffer, format) { try { return new Blob(buffer, {type: format}); } catch (e) { var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder); buffer.forEach(function(buf) { bb.append(buf); }); return bb.getBlob(format); } } /** * Get formdata */ function getFormData() { var isNeedShim = ~navigator.userAgent.indexOf('Android') && ~navigator.vendor.indexOf('Google') && !~navigator.userAgent.indexOf('Chrome') && navigator.userAgent.match(/AppleWebKit//(/d+)/).pop() <= 534; return isNeedShim ? new FormDataShim() : new FormData(); } /** * formdata patch, patch android machines that do not support formdata upload blobs* @constructor */ function FormDataShim() { console.warn('using formdata shim'); var o = this, parts = [], boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36), oldSend = XMLHttpRequest.prototype.send; this.append = function(name, value, filename) { parts.push('--' + boundary + '/r/nContent-Disposition: form-data; name="' + name + '"'); if (value instanceof Blob) { parts.push('; filename="' + (filename || 'blob') + '"/r/nContent-Type: ' + value.type + '/r/n/r/n'); parts.push(value); } else { parts.push('/r/n/r/n' + value); } parts.push('/r/n'); }; // Override XHR send() XMLHttpRequest.prototype.send = function(val) { var fr, data, oXHR = this; if (val === o) { // Append the final boundary string parts.push('--' + boundary + '--/r/n'); // Create the blob data = getBlob(parts); // Set up and read the blob into an array to be sent fr = new FileReader(); fr.onload = function() { oldSend.call(oXHR, fr.result); }; fr.onerror = function(err) { throw err; }; fr.readAsArrayBuffer(data); // Set the multipart content type and boudary this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary); XMLHttpRequest.prototype.send = oldSend; } else { oldSend.call(this, val); } }; }</script>(3) The upload image jsp page related code of the kindeditor plug-in.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ page import="java.util.*,java.io.*" %><%@ page import="java.text.SimpleDateFormat" %><%@ page import="org.apache.commons.fileupload.*" %><%@ page import="org.apache.commons.fileupload.disk.*" %><%@ page import="org.apache.commons.fileupload.servlet.*" %><%@ page import="org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%><%@ page import="org.json.simple.*" %><%/** * KindEditor JSP * * This JSP program is a demonstration program, and it is recommended not to use it directly in actual projects. * If you are sure to use this program directly, please carefully confirm the relevant security settings before using it. * *///File save directory path String savePath = pageContext.getServletContext().getRealPath("/") + "attached/";//String savePath = "http:////192.168.1.226:8080//qslnbase//uploadFile/";//String savePath = "D:/WWW/qslnADP/ADP/WebRoot/kindeditor/attached/";//File save directory URLString saveUrl = request.getContextPath() + "/attached/";//Define the file extension that is allowed to be uploaded HashMap<String, String> extMap = new HashMap<String, String>();extMap.put("image", "gif,jpg,jpeg,png,bmp,blob");extMap.put("flash", "swf,flv");extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");//Maximum file size long maxSize = 1000000;response.setContentType("text/html; charset=UTF-8");if(!ServletFileUpload.isMultipartContent(request)){ out.println(getError("Please select file.")); return;}//Check directory File uploadDir = new File(savePath); if(!uploadDir.isDirectory()){ out.println(getError("UploadDir.canWrite())); return;}//Check directory write permissions if(!uploadDir.canWrite()){ out.println(getError("UploadDir.No write permissions.")); return;}String dirName = request.getParameter("dir"); if (dirName == null) { dirName = "image";}if(!extMap.containsKey(dirName)){ out.println(getError("Dir" directory name is incorrect. ")); return;}//Create folder savePath += dirName + "/";saveUrl += dirName + "/";File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs();}SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");String ymd = sdf.format(new Date());savePath += ymd + "/";saveUrl += ymd + "/";File dirFile = new File(savePath);if (!dirFile.exists()) { dirFile.mkdirs();}//Struts2 Request wrapper filter MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;//Get the uploaded file name String fileName1 = wrapper.getFileNames("upload")[0];//Get file filter File file = wrapper.getFiles("upload")[0];//Check file size if(file.length() > maxSize){ out.println(getError("Upload file size exceeds the limit.")); return;}//Check the extension String fileExt1 = fileName1.substring(fileName1.lastIndexOf(".") + 1).toLowerCase();//Refactor the upload file name SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmss");String newFileName1 = df1.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt1;byte[] buffer = new byte[1024];//Get file output stream FileOutputStream fos = new FileOutputStream(savePath + newFileName1);String url=savePath + newFileName1;out.println(url);//Get current file input stream in memory InputStream in = new FileInputStream(file);try { int num = 0; while ((num = in.read(buffer)) > 0) { fos.write(buffer, 0, num); }} catch (Exception e) { e.printStackTrace(System.err);} finally { in.close(); fos.close();}%><%!private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); return obj.toJSONString();}%> ( 4) The jar package for uploading pictures by kindeditor is as follows
A.commons-fileupload-1.2.1.jar
B.commons-io-1.4.jar
C.json_simple-1.1.jar
There is no js code about kindeditor used here. For details, please refer to: Kinditor implements automatic image upload function.
(5) The div for uploading pictures by kindeditor is as follows
<div id="div2"> <ul> <li id="wy"> <img style="height:100%;width:100%;position:absolute;top:0px;" src="<%=request.getContextPath()%>/shequ/images/index.png;" > </li> </ul> </div>
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.