java webApp asynchronous upload image implementation code
- 2020-05-16 06:58:48
- OfStack
How to achieve java webApp asynchronously upload pictures, first understand the following questions:
1. Picture upload;
2. Picture upload preview;
3. Upload picture change address asynchronously add to database;
The main content
This example mainly USES the pure HTML front end and JavaScript code as tools. The code sample of demo's image upload implementation is as follows:
(1) click the div code of the uploaded image:
<div id="div1" class="photo">
<input type="file" id="choose" accept="image/*" multiple >
<a id="upload"> To upload pictures </a>
<a class="myinputimg" onclick="selectphoto();"> Select from the gallery </a>
<a class="myinputimg" id="back"> cancel </a>
</div>
(2) javaScript code
<script type="text/javascript">
// Get the uploaded image input The form elements
var filechooser = document.getElementById("choose");
// Create for compressing the image canvas
var canvas = document.createElement("canvas");
// To obtain canvas Visual properties
var ctx = canvas.getContext('2d');
// tiles canva
var tCanvas = document.createElement("canvas");
var tctx = tCanvas.getContext("2d");
// Canvas size
var maxsize = 100 * 1024;
// Upload image click event
$("#upload").on("click", function() {
filechooser.click();
})
.on("touchstart", function() {
// Add element attributes
$(this).addClass("touch");
})
.on("touchend", function() {
// Remove element attributes
$(this).removeClass("touch");
});
// Element changes
filechooser.onchange = function() {
// If the selection is null, return the operation
if (!this.files.length) return;
// Create an array of uploaded images
var files = Array.prototype.slice.call(this.files);
// Select the number greater than 1 Open, reverse operation, here according to the requirements set; pc The test 1 Can upload a number of pictures, mobile terminal selection 1 Zhang, the page can only be previewed 1 Zhang. Since it is a mobile terminal, make this judgment.
if (files.length >1) {
alert("1 Secondary upload only 1 image ");
return;
}
// Traverse the uploaded image file array, you don't need to traverse, directly access can.
files.forEach(function(file, i) {
// Determine image format
if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
var reader = new FileReader();
var li = document.createElement("li");
// Get image size
var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
// Preview picture
li.innerHTML = '<div class="progress"><span></span></div><div class="size">' + size + '</div>';
// Add image preview code;
$(".img-list").append($(li));
reader.onload = function() {
var result = this.result;
var img = new Image();
img.src = result;
// Picture shows
$(li).css("background-image", "url(" + result + ")");
// If the image size is less than 100kb , then upload directly
if (result.length <= maxsize) {
img = null;
upload(result, file.type, $(li));
return;
}
// After loading the image, compress it and 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 the image compression related;
// use canvas Compress the large image
function compress(img) {
var initSize = img.src.length;
var width = img.width;
var height = img.height;
// If the picture is greater than 4 Megapixels, calculate the compression ratio and press the size to 400 All of the following
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;
// With the base
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// If the image is larger than pixels 100 Wan USES tiles
var count;
if ((count = width * height / 1000000) > 1) {
count = ~~(Math.sqrt(count) + 1); // Calculate how many tiles to divide into
// Calculate the width and height of each tile
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);
}
// Minimum compression
var ndata = canvas.toDataURL('image/jpeg', 0.1);
console.log(' Before compression: ' + initSize);
console.log(' After the compression: ' + ndata.length);
console.log(' The compression rate: ' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
return ndata;
}
// Picture upload, will base64 The picture turned into 2 Base object, insert formdata upload
function upload(basestr, type, $li) {
var text = window.atob(basestr.split(",")[1]);
var buffer = new Uint8Array(text.length);
var pecent = 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);
// An asynchronous request kindeditor Upload image of plugin jsp page
xhr.open('post', '<%=request.getContextPath()%>/kindeditor/jsp/upload_json.jsp');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Returns the image address on the server side
var face_img=xhr.responseText;
var id=$("#arId").text();
// Asynchronously add a picture to the database
$.ajax({
type:"POST",
// An asynchronous request Struts the action Class inserts the image address into the database
url:"add_article_faceurl.action",
dataType:"json",
data:"faceurl="+face_img+"&id="+id,
async:true,
success: function(msg){
// Gets the image associated with the add database id Value into the hidden area of the page
$("#arId").text(msg);
},
error: function(a){}
});
}
};
// Simulated upload progress display
// Data delivery schedule, before 50% Show the progress
xhr.upload.addEventListener('progress', function(e) {
if (loop) return;
pecent = ~~(100 * e.loaded / e.total) / 2;
$li.find(".progress span").css('width', pecent + "%");
if (pecent == 50) {
mockProgress();
}
}, false);
// After the data 50% Simulate progress
function mockProgress() {
if (loop) return;
loop = setInterval(function() {
pecent++;
$li.find(".progress span").css('width', pecent + "%");
if (pecent == 99) {
clearInterval(loop);
}
}, 100);
}
xhr.send(formdata);
}
/**
* To obtain blob Object compatibility
* @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);
}
}
/**
* To obtain 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 The patch , For does not support formdata upload blob the android Machine patch
* @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 code of jsp page of the uploaded picture of 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 The program is a demonstration program and is not recommended to be used directly in real projects.
* If you are sure to use this program directly, please carefully confirm the relevant security Settings before using it.
*
*/
// The file saves the 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 URL
String saveUrl = request.getContextPath() + "/attached/";
// Defines the file extensions that are 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 the file. "));
return;
}
// Check the directory
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
out.println(getError(" The upload directory does not exist. "));
return;
}
// Check directory write permissions
if(!uploadDir.canWrite()){
out.println(getError(" Upload directory without write permission. "));
return;
}
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
if(!extMap.containsKey(dirName)){
out.println(getError(" The directory name is incorrect. "));
return;
}
// Create folders
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 Packing filter
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
// For the upload The name of the file
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 over limit. "));
return;
}
// Check the extension
String fileExt1 = fileName1.substring(fileName1.lastIndexOf(".") + 1).toLowerCase();
// Refactor upload file name
SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName1 = df1.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt1;
byte[] buffer = new byte[1024];
// Gets the file output stream
FileOutputStream fos = new FileOutputStream(savePath + newFileName1);
String url=savePath + newFileName1;
out.println(url);
// Gets the 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 of pictures uploaded by kindeditor is shown below
A.commons-fileupload-1.2.1.jar
B.commons-io-1.4.jar
C.json_simple-1.1.jar
The js code about kindeditor is not used here, for details, please refer to: Kindeditor realizes the automatic image upload function
(5) div for kindeditor upload image preview is as follows
<div id="div2">
<ul class="img-list">
<li id="wy">
<img style="height:100%;width:100%;position:absolute;top:0px;" src="<%=request.getContextPath()%>/shequ/images/index.png;" >
</li>
</ul>
</div>